一:对象关系教程查询
一个 Query
创建对象时使用
方法Session的
query()
。此函数接受一个变量数量的参数,可以是任何类和class-instrumented描述符的组合。
Query返回的是元组,可以像普通Python对象一样,元组返回一个属性的名字或者一个类的类名
1)Query
它加载User
实例
for instance in session.query(User).order_by(User.id): print(instance.name,instance.fullname) ---------------------------------------------------------------- ed tianshi shi shi jone san san jone jun jun jone
2)ORM-instrumented描述符作为参数
for name,fullname in session.query(User.name,User.fullname): print(name,fullname) ---------------------------------------------------------------- ed tianshi shi shi jone san san jone jun jun jone
for row in session.query(User,User.name).all(): print(row.User,row.name) ---------------------------------------------------------- name:ed full name:tianshi password:123456 ed name:shi full name:shi jone password:123456 shi name:san full name:san jone password:123456 san name:jun full name:jun jone password:123456 jun
4) 通过label()返回属性列重命名
for row in session.query(User.name.label("new_name")).all(): print(row.new_name) -------------------------------------------------------------------------- ed shi san jun
5)通过aliased()
把实例重命名
from sqlalchemy.orm import aliased user_alias=aliased(User,name="user_alias") #把类实例重命名为user_alias for row in session.query(user_alias,user_alias.name).all(): print(row.user_alias) -------------------------------------- name:ed full name:tianshi password:123456 name:shi full name:shi jone password:123456 name:san full name:san jone password:123456 name:jun full name:jun jone password:123456
6)Query
包括可以使用limit和offset,最方便的使用Python数组切片
for u in session.query(User).order_by(User.id)[1:3]:
表示从第1条后面开始查询2条 不包括3
print(u.id)
-----------------------------------------
2
3
7)query查询结果过滤filter_by()和filter()。filter可以支持更多查询条件,注意写法上不同。
#filter_by查询 for name, in session.query(User.name).filter_by(fullname="shi jun2"): print(name) #filter查询 for name,in session.query(User.name).filter(User.fullname=="shi jun2"): print(name) #filter复合查询,这里相当于and查询 for user in session.query(User).filter(User.name=='shi2').filter(User.fullname=='shi jun2'): print(user) 结果: shi2 shi2 User<name:shi2 fullname:shi jun2 password:123456>
二: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()