Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row count in MySQLdb

Is there a better way to get the row count than doing the following?

cursor.execute("SELECT DISTINCT(provider_id) FROM main_iteminstance")
num_items = len(cursor.fetchall())

Is there a shorthand in MySQLdb for the above?

like image 898
David542 Avatar asked Dec 05 '25 03:12

David542


2 Answers

You could execute the following SQL directly on cursor.execute rather than depending on MySQLdb:

cursor.execute("SELECT COUNT(DISTINCT provider_id) FROM main_iteminstance")

Then you just get the result from that query.

like image 163
ppp Avatar answered Dec 07 '25 15:12

ppp


The result of cursor.execute returns the number of rows returned by the query so just assign to a variable.

num_items = cursor.execute("SELECT DISTINCT(provider_id) FROM main_iteminstance")

This will also work and you won't have to run an extra query just to get the number of items

like image 35
Arpit Avatar answered Dec 07 '25 16:12

Arpit