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

Python中mysql-connector创建关联存储过程遇命令同步错误的解决

解决mysql-connector创建存储过程时的"Commands out of sync"错误

问题场景

使用Python的mysql-connector连续创建两个存储过程(第二个调用第一个),代码如下:

def ExecuteQueryFromFile(query_name, path):
  try:
    with open(path, "r") as file:
        sql_script = file.read()
    cursor.execute(sql_script)
    result_set = cursor.fetchall()
  except Exception as e:
    print("An error occurred while executing " + query_name + ": {}".format(e))
    cursor.close()
    sepix_db_conn.close()
    sys.exit(1)
  print(query_name + " completed successfully.")

ExecuteQueryFromFile("sp1.sql", sp1Path)
ExecuteQueryFromFile("sp2.sql", sp2Path)

执行第二个存储过程创建语句时触发异常:

An error occurred while executing sp2.sql: 2014 (HY000): Commands out of sync; you can't run this command now

尝试过添加fetchall()、提交事务、重新创建游标,问题依旧。

解决方案

问题根源

创建存储过程属于DDL操作,不会返回结果集,fetchall()不仅无效,还会让游标处于异常状态;即使提交事务,游标仍可能残留未清理的状态标记,导致后续执行报错。

正确处理步骤

  1. 移除无用的fetchall()调用:因为创建存储过程无结果集,强行调用会干扰游标状态。
  2. 清理游标剩余状态:执行完DDL语句后,调用cursor.nextset()遍历所有可能的空结果集,重置游标状态。
  3. 显式提交事务:虽然MySQL默认自动提交DDL,但显式提交能确保连接状态完全同步。

修改后的代码

def ExecuteQueryFromFile(query_name, path):
    try:
        with open(path, "r") as file:
            sql_script = file.read()
        cursor.execute(sql_script)
        # 清理游标状态,遍历所有剩余结果集(即使为空)
        while cursor.nextset():
            pass
        # 显式提交事务,确保状态同步
        sepix_db_conn.commit()
    except Exception as e:
        print(f"An error occurred while executing {query_name}: {e}")
        cursor.close()
        sepix_db_conn.close()
        sys.exit(1)
    print(f"{query_name} completed successfully.")

ExecuteQueryFromFile("sp1.sql", sp1Path)
ExecuteQueryFromFile("sp2.sql", sp2Path)

额外注意事项

如果你的存储过程SQL脚本中包含DELIMITER切换语句(如DELIMITER //),需要移除这些语句。因为mysql-connector会将整个脚本作为单个语句发送给服务器,服务器能自动解析BEGIN...END块内的分号,无需手动切换分隔符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:05:22