Python:受cursor.execute影响的行数(“SELECT …”)

如何访问受影响的行数:

cursor.execute("SELECT COUNT(*) from result where 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() 

result将保存一个元素, COUNT(*)的值。 所以find行数:

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

从通常由Python数据库API实现的PEP 249开始 :

游标对象应该响应以下方法和属性:

[…]

.rowcount
此只读属性指定最后一个.execute *()产生的行数(对于DQL语句(如'select')或受影响(对于'update'或'insert'等DML语句))。

希望这是你的意思。

受影响的行数从execute中返回:

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

当然,正如AndiDog已经提到的那样,您可以随时访问游标的rowcount属性来获取行计数,以获取最后一次执行的计数:

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

从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 """ 

在我看来,获得选定行数量的最简单方法如下:

当使用获取命令(fetchall(),fetchone(),fetchmany())时,游标对象返回一个带有结果的列表。 要获得选定的行,只需打印此列表的长度。 但是这对于fetchall()来说是有意义的。 😉

例:

 print len(cursor.fetchall) 

对于mysql最简单的方法是这样的

 mycur.execute("SELECT COUNT(*) FROM osreport") print(mycur.fetchall()) 

//这适用于我。 你可以用这种方式

 query = "select count(id) from test" cursor.execute(query) var = cursor.fetchone () print var[0]