pythonsqlrowsdatabase

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+"_%'")

Solution

  • 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()