Python,如何检查结果集是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16561362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:00:06  来源:igfitidea点击:

Python, how to check if a result set is empty?

pythonresultsetpython-db-api

提问by Tao Venzke

I have a sql statement that returns no hits. For example, 'select * from TAB where 1 = 2'.

我有一个不返回任何命中的 sql 语句。例如,'select * from TAB where 1 = 2'

I want to check how many rows are returned,

我想检查返回了多少行,

cursor.execute(query_sql)

rs = cursor.fetchall()

Here I get already exception: "(0, 'No result set')"

在这里我已经得到异常:“(0,'无结果集')”

How can I prevend this exception, check whether the result set is empty?

如何防止此异常,检查结果集是否为空?

采纳答案by Martijn Pieters

cursor.rowcountwill usually be set to 0.

cursor.rowcount通常会设置为 0。

If, however, you are running a statement that would neverreturn a result set (such as INSERTwithout 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.

但是,如果您正在运行一个永远不会返回结果集的语句(例如INSERTwithout RETURNING, or SELECT ... INTO),那么您不需要调用.fetchall(); 这样的语句不会有结果集。调用.execute()足以运行该语句。



Note that database adapters are also allowed to set the rowcount to -1if the database adapter can't determine the exact affected count. See the PEP 249 Cursor.rowcountspecification:

请注意,-1如果数据库适配器无法确定确切的受影响计数,则还允许数据库适配器将行计数设置为。请参阅PEP 249Cursor.rowcount规范

The attribute is -1in case no .execute*()has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface.

该属性用于在游标上未执行-1任何.execute*()操作或接口无法确定最后一次操作的行数的情况下。

The sqlite3libraryis prone to doing this. In all such cases, if you must know the affected rowcount up front, execute a COUNT()select in the same transaction first.

sqlite3是容易发生这样做。在所有这些情况下,如果您必须预先知道受影响的行数,COUNT()请先在同一事务中执行选择。

回答by thavan

MySQLdb will not raise an exception if the result set is empty. Additionally cursor.execute() function will return a long value which is number of rows in the fetched result set. So if you want to check for empty results, your code can be re-written as

如果结果集为空,MySQLdb 不会引发异常。此外, cursor.execute() 函数将返回一个 long 值,它是获取的结果集中的行数。所以如果你想检查空结果,你的代码可以重写为

rows_count = cursor.execute(query_sql)
if rows_count > 0:
     rs = cursor.fetchall()
else:
     // handle empty result set

回答by Rockallite

Notice:This is for MySQLdb module in Python.

注意:这是针对 Python 中的 MySQLdb 模块。

For a SELECTstatement, there shouldn't be an exception for an empty recordset. Just an empty list ([]) for cursor.fetchall()and Nonefor cursor.fetchone().

对于SELECT语句,不应该有空记录集的例外。只是一个空列表 ( []) forcursor.fetchall()Nonefor cursor.fetchone()

For any other statement, e.g. INSERTor UPDATE, that doesn't return a recordset, you can neither call fetchall()nor fetchone()on the cursor. Otherwise, an exception will be raised.

对于不返回记录集的任何其他语句,例如INSERTor UPDATE,您既不能调用fetchall()也不能fetchone()在游标上。否则,将引发异常。

There's one way to distinguish between the above two types of cursors:

有一种方法可以区分上述两种类型的游标:

def yield_data(cursor):
    while True:
        if cursor.description is None:
            # No recordset for INSERT, UPDATE, CREATE, etc
            pass
        else:
            # Recordset for SELECT, yield data
            yield cursor.fetchall()
            # Or yield column names with
            # yield [col[0] for col in cursor.description]

        # Go to the next recordset
        if not cursor.nextset():
            # End of recordsets
            return

回答by Ryan Tuck

if you're connecting to a postgres database, the following works:

如果您要连接到 postgres 数据库,则以下操作有效:

result = cursor.execute(query)

if result.returns_rows:
    # we got rows!
    return [{k:v for k,v in zip(result.keys(), r)} for r in result.rows]
else:
    return None

回答by Anand Kumar Singh

You can do like this :

你可以这样做:

count = 0
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=serverName;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute(SQL query)
for row in cursor:
    count = 1
    if true condition:
        print("True")
    else:
        print("False")
if count == 0:
    print("No Result")

Thanks :)

谢谢 :)

回答by Piney

I had issues with rowcount always returning -1 no matter what solution I tried.

无论我尝试什么解决方案,我都遇到了 rowcount 总是返回 -1 的问题。

I found the following a good replacement to check for a null result.

我发现以下一个很好的替代品来检查空结果。

c.execute("SELECT * FROM users WHERE id=?", (id_num,))
row = c.fetchone()
if row == None:
   print("There are no results for this query")