一:filter常用操作
1) equals
query.filter(User.name == ‘ed‘)
2) not equals
query.filter(User.name != ‘ed‘)
3) LIKE 是区分大小写的
query.filter(User.name.like(‘%ed%‘))
4) ILIKE 不区分大小写的
query.filter(User.name.ilike(‘%ed%‘))
5) 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%‘))
))
6) NOT IN
query.filter(~User.name.in_([‘ed‘, ‘wendy‘, ‘jack‘]))
7) IS NULL
query.filter(User.name == None) query.filter(User.name.is_(None))
8)IS NOT NULL
query.filter(User.name != None) query.filter(User.name.isnot(None))
9) 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‘)
10) OR
from sqlalchemy import or_ query.filter(or_(User.name == ‘ed‘, User.name == ‘wendy‘))
11)MATCH
match()使用一个特定于数据库的 MATCH或 CONTAINS函数;它的行为会有所不同后端和不可用等后端SQLite。 query.filter(User.name.match(‘wendy‘))
二:返回结果
Query发出SQL语句和返回包括数据库结果一个值
print(session.query(User.name).filter(User.fullname=="shi jun2")) -------------------------------------------- SELECT users.name AS users_name FROM users WHERE users.fullname = %(fullname_1)s
1)all()取出所的记录
2)first()返回第一条记录
3)one():不存在,或者有多行记录的时候报错(no items found,multiple items found
4)one_or_none():如果有一条记录就返回一条记录,如果没有记录就返回NONE
5)scalar()调用 one()方法,成功返回只有一行结果的第1列
query=session.query(User.name).first() print(query) (‘shi‘,) query=session.query(User.name).all() print(query) [(‘shi‘,), (‘shi2‘,)] query=session.query(User.name).one() print(query) sqlalchemy.orm.exc.MultipleResultsFound: Multiple rows were found for one() query=session.query(User.name).filter(User.name=="shi").one()#这里查询出的结果只有1条,所以不会报错 print(query) (‘shi‘,) 如果有一条记录就返回一条记录,如果没有记录就返回NONE query=session.query(User.name).filter(User.name=="shi").one_or_none() (‘shi‘,) print(query) query=session.query(User.name).filter(User.name=="sh3").one_or_none() print(query) None query=session.query(User.name).filter(User.name=="shi").scalar() print(query) shi
三:Query通过text()可以使用字符串
# for user in session.query(User).filter(text("id<224")).order_by(text("id")).all(): # print(user) #通过params传递参数,使用:来分开参数 # for user in session.query(User).filter(text("id>:value and name=:name")).params(value=1,name="fred").order_by(User.id).one(): # print(user) for user in session.query(User).from_statement(text("select * from users where name=:name")).params(name="shi").all(): print(user)
四:count()方法用于确定SQL语句将返回多少行
print(session.query(User).filter(User.name.like("shi%")).count()) 使用func.count()统计 from sqlalchemy import func for row in session.query(func.count(User.name),User.name).group_by(User.name).all(): print(row) ------------ (1, ‘shi‘) (1, ‘shi2‘) select count(*) from table ==session.query(func.count(‘*‘)).select_from(User).scalar()
时间: 2024-10-14 06:25:09