如何检查结果集是否为空? [英] How to check if a result set is empty?
问题描述
我有一个不返回任何命中的 sql 语句.例如,'select * from TAB where 1 = 2'
.
I have a sql statement that returns no hits. For example, 'select * from TAB where 1 = 2'
.
我想查看返回了多少行,
I want to check how many rows are returned,
cursor.execute(query_sql)
rs = cursor.fetchall()
这里我已经得到了异常:(0,'无结果集')"
Here I get already exception: "(0, 'No result set')"
如何防止这个异常,检查结果集是否为空?
How can I prevend this exception, check whether the result set is empty?
推荐答案
cursor.rowcount
通常会设置为 0.
但是,如果您运行的语句从不返回结果集(例如 INSERT
没有 RETURNING
,或 SELECT ... INTO
),则不需要调用.fetchall()
;这样的语句不会有结果集.调用 .execute()
足以运行该语句.
If, however, you are running a statement that would never return a result set (such as INSERT
without RETURNING
, or SELECT ... INTO
), then you do not need to call .fetchall()
; there won't be a result set for such statements. Calling .execute()
is enough to run the statement.
请注意,如果数据库适配器无法确定确切的受影响计数,也允许数据库适配器将行数设置为 -1
.请参阅 PEP 249 Cursor.rowcount
规范:
Note that database adapters are also allowed to set the rowcount to -1
if the database adapter can't determine the exact affected count. See the PEP 249 Cursor.rowcount
specification:
属性为-1
,以防没有.execute*()
对游标执行过或者接口无法确定上次操作的行数.
The attribute is
-1
in case no.execute*()
has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface.
sqlite3
库 倾向于这样做.在所有此类情况下,如果您必须预先知道受影响的行数,请先在同一事务中执行 COUNT()
选择.
这篇关于如何检查结果集是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!