Python:cursor.execute影响的行数(“SELECT ...” [英] Python: Number of rows affected by cursor.execute("SELECT ...)

查看:4532
本文介绍了Python:cursor.execute影响的行数(“SELECT ...”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问受影响的行数:

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


解决方案

尝试使用 fetchone

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

结果元素, COUNT(*)的值。
所以找到行数:

  number_of_rows = result [0] 



或者,如果你愿意一下子做:

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

PS。这也是一个好的习惯,尽可能使用参数化参数,因为它可以在需要时自动引用参数,并防止sql注入。



参数化参数的正确语法取决于在你的python /数据库适配器(例如mysqldb,psycopg2或sqlite3)。它看起来像

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

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

解决方案

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

这篇关于Python:cursor.execute影响的行数(“SELECT ...”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆