您的位置:首页 > 编程语言 > Python开发

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

2017-09-25 17:28 302 查看
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()


shareimprove
this answer

https://stackoverflow.com/questions/2511679/python-number-of-rows-affected-by-cursor-executeselect

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐