返回列表和标量


Query 对象有许多方法可以立即发出 SQL 并返回包含加载的数据库结果的值。

以下是返回列表和标量的简要概述 -

全部()

它返回一个列表。下面给出的是 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

第一的()

它应用 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。

一()

此命令完全获取所有行,如果结果中不存在一个对象标识或复合行,则会引发错误。

session.query(Customers).one()

发现多行 -

MultipleResultsFound: Multiple rows were found for one()

没有找到行 -

NoResultFound: No row was found for one()

one() 方法对于希望以不同方式处理“未找到项目”和“找到多个项目”的系统非常有用。

标量()

它调用 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 = ?