命令不同步
如果遇到“命令不同步”错误,将无法在你的客户端代码中运行该命令,你正在以错误顺序调用客户端函数。
例如,如果你正使用mysql_use_result(),并打算在调用mysql_free_result()之前执行新查询,就会出现该问题。
如果你试图执行两次查询,但并未在两次查询之间调用mysql_use_result()或mysql_store_result(),也会出现该问题。
总结我的问题,
在存在select的语句中,如"select * from……","select func_xxx()"需要使用mysql_store_result()或mysql_use_result
用mysql C API 调用存储过程,并返回结果集。需要注意几个问题:
在建立链接的时候要加选项CLIENT_MULTI_STATEMENTS 或 CLIENT_MULTI_RESULTS,以便可以让query执行多个语句。
mysql_real_connect(mySQL,serverIP,user,password,database,serverPort,NULL,CLIENT_MULTI_STATEMENTS)
当query时可能产生错误error:2014 Commands out of sync; you can't run this command now
Mysql文档中说明错误:Commands out of sync
If you get Commands out of sync; you can't run this command now in your client code, you are calling client functions in the wrong order.
This can happen, for example, if you are using mysql_use_result() and try to execute a new query before you have called mysql_free_result(). It can also happen if you try to execute two queries that return data without calling mysql_use_result() or mysql_store_result() in between.
当执行完query后,mysql将结果集放在一个result集中,产生以上问题的原因有两个:
一是未将MYSQL_RES所指对象释放,即在下次查询时要mysql_free_result();
二是结果result集不为空,这个原因比较隐蔽。解决方法可以用如下写法:
do
{
/* Process all results */
printf("total affected rows: %lld", mysql_affected_rows(mysql));
...
if (!(result= mysql_store_result(mysql)))
{
printf(stderr, "Got fatal error processing query/n");
exit(1);
}
process_result_set(result); /* client function */
mysql_free_result(result);
} while (!mysql_next_result(mysql));
还有个问题感觉比较奇怪,我调用一个存储过程,存储过程中就一句select
Create procedure test()
Begin
Select * from test ;
End ;
用以上方法处理结果集循环会执行两次,开始我只调了一次result= mysql_store_result(mysql)),导致以后执行query报2014错误。
错误场景:
使用Python开发的数据库升级工具,在升级脚本行遇到如下语句报错了:
- 1
- 2
- 3
- 4
- 5
- 6
先解释下这段语句,alarmeventlog
表示原始报警日志,alarmclientlog
表示报警处理日志。当alarmclientlog
插入或更新后,要把处理结果也同步到alarmeventlog
里面去。
因此,我创建一个触发器做同步操作,为防止之前已经有此触发器,我先检查并删除下。
问题定位:
在网上搜到如下有用的资料:
Python’s MySQLdb 2014 Error – Commands out of sync
这里面说可能跟多条语句放在一起执行有关。
但是有些语句是可以放在一起执行的,那是不是对SQL语句的类型由要求?
然后我找到了这个帖子,是创建存储过程时发现的:
Python, “commands out of sync; you can’t run this command now”
这位也一样:
解决error:2014 Commands out of sync; you can’t run this command now
其他错误:
2014 - Commands out of sync; you can’t run this command now
解决问题:
综上所述,我感觉触发器、存储过程、SHOW等命令语句不能放一起执行。【待查】
解决方案是把语句分开执行。
在MySQL的官网手册,我发现了这个问题的说明: