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

后端 未结 7 1364
予麋鹿
予麋鹿 2021-02-02 05:26

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,

cu         


        
7条回答
  •  眼角桃花
    2021-02-02 06:11

    cursor.rowcount will usually be set to 0.

    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.


    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:

    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.

    The sqlite3 library is 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.

提交回复
热议问题