操作存储过程连接代码
错误代码:
Commands out of sync; you can't run this command now
DB_Param mDB("192.168.1.254", "admin", "admin", "node", 3306, NULL, CLIENT_MULTI_STATEMENTS );//CLIENT_MULTI_RESULTS);
CMysql mysql(mDB);
bool CMysql::ConnectDB(DB_Param* p)
{
if(!mysql_real_connect(&mysql,(p->mStrHost).c_str(),p->mStrUser.c_str(),p->mStrPassword.c_str(),p->mStrDB.c_str(),p->mIPort,p->unix_socket,p->client_flag))
{
return false;
}
return true;
}
上面的最后一个参数,需要使用
CLIENT_MULTI_STATEMENTS )或者CLIENT_MULTI_RESULTS)
C++操作MySQL存储过程中,出现如下错误
Commands out of sync; you can't run this command now
原因应该是MYSQL_RES 结果在下一次查询的时候没有被释放掉,所以出现该错误
官方解释如下:
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));
上面的代码在我的程序中没有成功。
我的解决方法:两种
第一种方法:调用一次查询函数,释放一次,做到每一次操作数据库,都重新连接一次数据库,用完该次操作立刻释放掉MYSQL_RES结果集
该方法,操作数据库频繁,效率相对不高
第二种方法:将所有的数据读到缓存中,对缓存进行读写,效率较高,空间换时间的一种做法。
两种方法都有各自的解决方法,取决于你的程序的实际情况。