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

使用mysql-connector-python执行二次查询时遇Commands out of sync错误

解决MySQL-Connector-Python的"Commands out of sync"错误

错误原因

当使用multi=True执行多条SQL语句时,cur.execute()会返回一个迭代器,用于逐个处理每条SQL的执行结果。如果不遍历完这个迭代器,游标会一直处于忙碌状态,无法执行后续SQL,从而触发2014 (HY000): Commands out of sync; you can't run this command now错误。

解决办法

必须遍历multi=True执行后的返回值,处理完所有语句的执行结果,让游标回到可用状态。

修改后的代码示例

from mysql.connector import connect

conn = connect(
    host="127.0.0.1",
    user="usr",
    password="pawrd",
    database="databse",
    port="3306"
)
cur = conn.cursor()  # 原代码遗漏创建游标步骤,需补上

with open("create_tables.sql") as query:
    # 执行多语句SQL,获取结果迭代器
    results = cur.execute(query.read(), multi=True)
    # 遍历迭代器,释放游标
    for _ in results:
        pass  # 若需查看执行结果,可在此添加处理逻辑,如打印受影响行数

# 现在可以正常执行后续查询
cur.execute("select 1")
print(cur.fetchone())

# 用完后关闭游标和连接
cur.close()
conn.close()

补充说明

  • 原代码遗漏了创建游标cur = conn.cursor()的关键步骤,这是使用游标执行SQL的前提,必须补上。
  • 遍历迭代器时,如果需要验证每张表的创建结果,可以在循环中添加逻辑,比如:
    for result in results:
        if result.with_rows:
            print(f"执行结果: {result.fetchall()}")
        else:
            print(f"受影响行数: {result.rowcount}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:55:19