Python:cursor.execute("SELECT ...)影响的行数

76 投票
7 回答
265545 浏览
提问于 2025-04-15 20:49

我该如何获取受影响的行数:

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

7 个回答

45

执行操作后,会返回受影响的行数:

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

    """
103

来自PEP 249的内容,通常由Python数据库API实现:

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

[…]

.rowcount
这个只读属性表示上一个执行的操作(比如用'选择'语句查询数据)产生了多少行结果,或者影响了多少行(比如用'更新'或'插入'语句修改数据)。

但要小心——接下来它说:

如果游标上没有执行过任何.execute*(),或者上一个操作的行数无法通过接口确定,那么这个属性的值就是-1。[7]

注意:
未来的数据库API规范可能会将这种情况重新定义为返回None,而不是-1。

所以,如果你已经执行了你的语句,而且它运行正常,并且你确定你的代码总是会在相同版本的数据库管理系统上运行,那么这个方法是合理的。

107

试试用 fetchone

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

result 会保存一个包含一个元素的元组,这个元素就是 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()

另外,尽量使用参数化的参数是个好习惯,因为这样可以在需要的时候自动为你加上引号,还能防止 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()

撰写回答