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

前端 未结 6 1395
迷失自我
迷失自我 2020-12-13 08:36

How can I access the number of rows affected by:

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


        
6条回答
  •  孤街浪徒
    2020-12-13 08:48

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

提交回复
热议问题