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()不仅无效,还会让游标处于异常状态;即使提交事务,游标仍可能残留未清理的状态标记,导致后续执行报错。
正确处理步骤
- 移除无用的
fetchall()调用:因为创建存储过程无结果集,强行调用会干扰游标状态。 - 清理游标剩余状态:执行完DDL语句后,调用
cursor.nextset()遍历所有可能的空结果集,重置游标状态。 - 显式提交事务:虽然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
相关产品推荐
相关产品推荐

