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