orm_sqlalchemy
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

73 lines
1.7 KiB

from sqlalchemy import select
from s1_models import *
# 方法1 rp = ResultProxy
# s1 = select([cookies]) # 2.0废弃
# rp1 = connection.execute(s1)
# results1 = rp1.fetchall()
# print(results1)
#
# # 方法2
# s2 = cookies.select()
# str(s2)
# rp2 = connection.execute(s2)
# results2 = rp2.fetchall()
# print(results2)
# print(results2[0])
# first_row = results2[0]
# print(first_row[1])
# print(first_row.cookie_name)
# print(first_row[cookies.c.cookie_name])
#
# 添加查询参数
s3 = select([cookies.c.cookie_name, cookies.c.quantity])
rp3 = connection.execute(s3)
print(rp3.keys())
results3 = rp3.fetchall()
print(results3)
result_dict = [dict(zip(rp3.keys(), r)) for r in results3]
print(result_dict)
# 排序
s4 = select([cookies.c.cookie_name, cookies.c.quantity]).order_by(cookies.c.quantity)
rp4 = connection.execute(s4)
for cookie in rp4:
print(f"{cookie.quantity} - {cookie.cookie_name}")
# 反向排序
from sqlalchemy import desc
s5 = select([cookies.c.cookie_name, cookies.c.quantity]).order_by(desc(cookies.c.quantity))
rp5 = connection.execute(s5)
for cookie in rp5:
print(f"{cookie.quantity} - {cookie.cookie_name}")
# limit
s6 = select([cookies.c.cookie_name, cookies.c.quantity]).order_by(cookies.c.quantity).limit(2)
rp6 = connection.execute(s6)
for cookie in rp6:
print(f"{cookie.quantity} - {cookie.cookie_name}")
# sum
from sqlalchemy import func
s7 = select([func.sum(cookies.c.quantity)])
print(str(s7))
rp7 = connection.execute(s7)
print(rp7.scalar())
# count
s8 = select([func.count(cookies.c.cookie_name)])
print(str(s8))
rp8 = connection.execute(s8)
print(rp8.scalar())
# as
s9 = select([func.count(cookies.c.cookie_name).label('cookie_count')])
rp9 = connection.execute(s9)
r = rp9.first()
print(list(r.keys()))
print(r.cookie_count)