📜  返回列表和标量

📅  最后修改于: 2020-11-27 07:48:09             🧑  作者: Mango


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

第一()

它应用一个限制,并将第一个结果作为标量返回。

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 = ?