C++操作存储过程 2014 问题 MySQL

操作存储过程连接代码

错误代码:

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结果集

该方法,操作数据库频繁,效率相对不高


第二种方法:将所有的数据读到缓存中,对缓存进行读写,效率较高,空间换时间的一种做法。


两种方法都有各自的解决方法,取决于你的程序的实际情况。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值