返回列表和标量
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()
它应用一个限制并将第一个结果作为标量返回。
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 = ?