Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Number of rows affected by cursor.execute("SELECT ...)

How can I access the number of rows affected by:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
like image 273
Tie-fighter Avatar asked Mar 24 '10 21:03

Tie-fighter


People also ask

Which method of cursor class is used to get the number of rows affected?

(A) cursor. rowcount - It returns the number of rows affected by DML statements.

Is read only property which returns the number of rows returned from SELECT statement?

This read-only property returns the number of rows returned for SELECT statements, or the number of rows affected by DML statements such as INSERT or UPDATE . For an example, see Section 10.5.

Which attribute is used to return number of rows that are affected by an execute () method?

Description ¶ PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

Which method of cursor class is used to get the number of rows affected after any of the insert update delete database operation executed from Python?

We can get number of rows affected by the query by using rowcount.


4 Answers

From PEP 249, which is usually implemented by Python database APIs:

Cursor Objects should respond to the following methods and attributes:

[…]

.rowcount
This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like 'select') or affected (for DML statements like 'update' or 'insert').

But be careful—it goes on to say:

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. [7]

Note:
Future versions of the DB API specification could redefine the latter case to have the object return None instead of -1.

So if you've executed your statement, and it works, and you're certain your code will always be run against the same version of the same DBMS, this is a reasonable solution.

like image 196
AndiDog Avatar answered Sep 20 '22 18:09

AndiDog


Try using fetchone:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'") result=cursor.fetchone() 

result will hold a tuple with one element, the value of COUNT(*). So to find the number of rows:

number_of_rows=result[0] 

Or, if you'd rather do it in one fell swoop:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'") (number_of_rows,)=cursor.fetchone() 

PS. It's also good practice to use parametrized arguments whenever possible, because it can automatically quote arguments for you when needed, and protect against sql injection.

The correct syntax for parametrized arguments depends on your python/database adapter (e.g. mysqldb, psycopg2 or sqlite3). It would look something like

cursor.execute("SELECT COUNT(*) from result where server_state= %s AND name LIKE %s",[2,digest+"_"+charset+"_%"]) (number_of_rows,)=cursor.fetchone() 
like image 43
unutbu Avatar answered Sep 16 '22 18:09

unutbu


The number of rows effected is returned from execute:

rows_affected=cursor.execute("SELECT ... ")

of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:

cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount

From the inline documentation of python MySQLdb:

 def execute(self, query, args=None):

    """Execute a query.

    query -- string, query to execute on server
    args -- optional sequence or mapping, parameters to use with query.

    Note: If args is a sequence, then %s must be used as the
    parameter placeholder in the query. If a mapping is used,
    %(key)s must be used as the placeholder.

    Returns long integer rows affected, if any

    """
like image 25
Boaz Avatar answered Sep 19 '22 18:09

Boaz


In my opinion, the simplest way to get the amount of selected rows is the following:

The cursor object returns a list with the results when using the fetch commands (fetchall(), fetchone(), fetchmany()). To get the selected rows just print the length of this list. But it just makes sense for fetchall(). ;-)

print len(cursor.fetchall)

# python3
print(len(cur.fetchall()))
like image 21
harvey_c Avatar answered Sep 18 '22 18:09

harvey_c