美文网首页
4.数据库常见的操作

4.数据库常见的操作

作者: 记事本的记事本 | 来源:发表于2019-04-26 18:30 被阅读0次

    常用的filter操作符
    下面的这些操作符可以应用在filter函数中

    equals:
    query.filter(User.name == 'ed')
    not equals:
    query.filter(User.name != 'ed')
    LIKE:
    query.filter(User.name.like('%ed%'))
    IN:
    query.filter(User.name.in_(['ed', 'wendy', 'jack']))

    works with query objects too:

    query.filter(User.name.in_(
    session.query(User.name).filter(User.name.like('%ed%'))
    ))
    NOT IN:
    query.filter(~User.name.in_(['ed', 'wendy', 'jack']))
    IS NULL:
    query.filter(User.name == None)

    alternatively, if pep8/linters are a concern

    query.filter(User.name.is_(None))
    IS NOT NULL:
    query.filter(User.name != None)

    alternatively, if pep8/linters are a concern

    query.filter(User.name.isnot(None))
    AND:

    use and_()

    from sqlalchemy import and_
    query.filter(and_(User.name == 'ed', User.fullname == 'Ed Jones'))

    or send multiple expressions to .filter()

    query.filter(User.name == 'ed', User.fullname == 'Ed Jones')

    or chain multiple filter()/filter_by() calls

    query.filter(User.name == 'ed').filter(User.fullname == 'Ed Jones')
    OR:
    from sqlalchemy import or_
    query.filter(or_(User.name == 'ed', User.name == 'wendy'))
    MATCH:
    query.filter(User.name.match('wendy'))

    增加数据

    arricle = Article(title="aaa",content="bbb")
    db.session.add(arricle)
    db.session.commit()
    

    查询数据

    result = Article.query.filter(Article.title=='mark').first()
    print(result.content)
    
    1. query是从db.Model中继承来的
    2. query.filter(Article.title=’xx’)过滤条件
    3. first()取出查询结果的第一条数据 实际上就是一个Article对象
    4. .all()是查询到的所有结果 是一个Article对象数组
    

    修改数据

    1. 查询到要改的数据 拿到Article对象
    2. 更新 article1.title=’new title’
    3. db.session.commit()
    
    result = Article.query.filter(Article.title=='success').first()
    old_title = result.title
    result.title = 'success2018'
    db.session.commit()
    

    删除

    1. 查出要删除的数据 拿到Article对象
    2. db.session.delete(article)
    3. db.session.commit()
    
    result = Article.query.filter(Article.title=='success2018').first()
    db.session.delete(result)
    db.session.commit()
    

    相关文章

      网友评论

          本文标题:4.数据库常见的操作

          本文链接:https://www.haomeiwen.com/subject/ovwqnqtx.html