SQLAlchemy教程

返回列表和标量

Query 对象有多种方法可以立即发出 SQL 并返回包含加载的数据库结果的值。
这是返回列表和标量的简要概述-

all()

它返回一个列表。下面给出了 all() 函数的代码行。
session.query(Customers).all()
Python 控制台显示以下发出的 SQL 表达式-
SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers

first()

它限制为 1 并以标量形式返回第一个结果。
SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
LIMIT ? OFFSET ?
LIMIT 的绑定参数为 1,OFFSET 的绑定参数为 0。

one()

此命令完全获取所有行,如果结果中不存在完全一个对象标识或复合行,则会引发错误。
session.query(Customers).one()
找到多行-
MultipleResultsFound: Multiple rows were found for one()
没有找到行-
NoResultFound: No row was found for one()
one() 方法对于希望以不同方式处理"未找到项目"和"找到多个项目"的系统很有用。

scalar()

它调用 one() 方法,成功后返回行的第一列,如下所示-
session.query(Customers).filter(Customers.id == 3).scalar()
这会生成以下 SQL 语句-
SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE customers.id = ?
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4