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

后端 未结 7 1217
予麋鹿
予麋鹿 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:17

    Notice: This is for MySQLdb module in Python.

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

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

    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
    

提交回复
热议问题