You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python的mysql.connector执行UPDATE后rowcount始终返回0的问题

MySQL UPDATE后cursor.rowcount始终返回0的解决方案

问题

执行代码中的UPDATE语句后,cursor.rowcount一直返回0,但相同SQL在TablePlus中能显示正确的更新行数。尝试调用MySQL的affected-rows方法但报错,不知道正确用法。

代码示例

import mysql.connector

def get_connection(host, user, password, db_name):
    connection = None
    try:
        connection = mysql.connector.connect(
            host=host,
            user=user,
            use_unicode=True,
            password=password,
            database=db_name

        )
        connection.set_charset_collation('utf8')
        print('Connected')
    except Exception as ex:
        print(str(ex))
    finally:
        return connection


with connection.cursor() as cursor:
  sql = 'UPDATE {} set underlying_price=9'.format(table_name)
  cursor.execute(sql)
  connection.commit()
  print('No of Rows Updated ...', cursor.rowcount)

解决办法

1. 先获取rowcount再执行commit

建议在cursor.execute()后立即获取rowcount,避免后续操作可能带来的影响:

with connection.cursor() as cursor:
    sql = 'UPDATE {} set underlying_price=9'.format(table_name)
    cursor.execute(sql)
    rows_updated = cursor.rowcount  # 先获取行数
    connection.commit()
    print('No of Rows Updated ...', rows_updated)

2. 使用Buffered Cursor

默认非缓冲游标在某些场景下可能无法正确返回rowcount,尝试切换为缓冲游标:

with connection.cursor(buffered=True) as cursor:
    sql = 'UPDATE {} set underlying_price=9'.format(table_name)
    cursor.execute(sql)
    print('No of Rows Updated ...', cursor.rowcount)
    connection.commit()

3. 开启FOUND_ROWS客户端标志

MySQL默认UPDATE返回实际值发生变化的行数,而TablePlus可能显示的是匹配到的行数。添加客户端标志让rowcount返回匹配行数:

# 修改get_connection里的连接代码
connection = mysql.connector.connect(
    host=host,
    user=user,
    use_unicode=True,
    password=password,
    database=db_name,
    client_flags=mysql.connector.ClientFlags.FOUND_ROWS  # 添加此行
)

4. 检查基础问题

  • 确认table_name变量无拼写错误,指向正确的表
  • 对比代码生成的SQL和TablePlus中执行的SQL,确保完全一致
  • 验证get_connection函数返回的是有效连接(未返回None)

关于affected-rows方法的正确调用

你提到的affected-rows方法仅适用于mysql-connector-python的C扩展版本,需通过连接对象调用:

with connection.cursor() as cursor:
    cursor.execute(sql)
    rows_updated = connection.affected_rows()  # 仅C扩展版本可用
    connection.commit()

内容的提问来源于stack exchange,提问作者Volatil3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 07:45:49