Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use num_rows() function in the MySQLDB API for Python?

Tags:

python

mysql

I have this statement

cursor = connection.cursor()
query = "SELECT * from table"
cursor.execute(query)
res = cursor.fetchall()
like image 708
Bingimar Avatar asked Oct 08 '10 12:10

Bingimar


People also ask

Does MySQLdb work with python3?

MySQLdb module, a popular interface with MySQL is not compatible with Python 3.

What is use of Fetchall () function?

fetchall() The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list. The following example shows how to retrieve the first two rows of a result set, and then retrieve any remaining rows: >>> cursor.

What is Python MySQLdb package?

What is MYSQLdb? MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2. 0 and is built on top of the MySQL C API. Packages to Install mysql-connector-python mysql-python.


2 Answers

cursor = connection.cursor()
query = "SELECT * from table"
cursor.execute(query)
print cursor.rowcount

According to the Python Database API Specification v2.0, the rowcount attribute of the cursor object should return the number of rows that the last query produced or affected (the latter is for queries that alter the database). If your database module conforms to the API specification, you should be able to use the rowcount attribute.

The num_rows() function you are looking for does not exist in the MySQLdb module. There is an internal module called _mysql which has a result class with a num_rows method, but you shouldn't be using that - the very existence of _mysql is considered an implementation detail.

like image 80
Tamás Avatar answered Oct 08 '22 01:10

Tamás


Most voted answer is not working yet. It should be like that:

cursor = connection.cursor()
query = "SELECT * FROM table"
cursor.execute(query)
cursor.fetchall()
print (cursor.rowcount)
like image 42
oğuzhan karabulut Avatar answered Oct 08 '22 02:10

oğuzhan karabulut