使用MYsql Conntector C++ 同一个连接不能多次操作数据库存储过程?

蜗牛的信仰 2015-08-27 11:24:30
我在使用mysql 的 mysql connector c++ 库 调用mysql的存储过程 中 出现了以下问题:

我的本意是保留一个 连接来多次操作 数据库 但是在第二次使用该连接操作数据库的时候 会抛出Commands out of sync; you can't run this command now 的异常。 测试代码 如下


#include "stdafx.h"
#include <driver/mysql_connection.h>
#include <driver/mysql_driver.h>
#include <cppconn/prepared_statement.h>
#pragma comment(lib,"mysqlconn/debug/mysqlcppconn.lib")

sql::Connection* g_conn = NULL;
void InitDB()
{
sql::Driver* driver = get_driver_instance();
sql::ConnectOptionsMap connection_properties;
connection_properties["hostName"] = std::string("tcp://192.168.10.10:3306");;
connection_properties["userName"] = std::string("admin");;
connection_properties["password"] = std::string("admin");;
connection_properties["schema"] = std::string("tcr_db");;
connection_properties["OPT_RECONNECT"] = true;
g_conn = driver->connect(connection_properties);
g_conn->setAutoCommit(0);
}
sql::ResultSet* Query(const char *szSql)
{
try
{
sql::PreparedStatement* prepStatement = g_conn->prepareStatement(szSql);
if (prepStatement)
{
return prepStatement->executeQuery();
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;;
}

return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
InitDB();
sql::ResultSet* pReSet1 = Query("CALL CheckHandleTask()");
if (pReSet1)
{
while (pReSet1->next())
{
std::cout << " 查询结果:" << pReSet1->getUInt("HandleID_") << std::endl;
}
}
delete pReSet1;
pReSet1 = NULL;


// 以下再进行调用 就会抛出 Commands out of sync; you can't run this command now 的异常。
sql::ResultSet* pReSet2 = Query("CALL test()");
if (pReSet2)
{
while (pReSet2->next())
{
std::cout << " 查询结果:" << pReSet2->getUInt("FileID_") << std::endl;
}
}
delete pReSet2;
pReSet2 = NULL;

getchar();
return 0;
}
...全文
231 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
mujiok2003 2015-08-27
  • 打赏
  • 举报
回复
prepStatement没有释放
蜗牛的信仰 2015-08-27
  • 打赏
  • 举报
回复
引用 1 楼 ant2012 的回复:
不懂,会不会 delete pReSet1; pReSet1 = NULL; 不需要释放,毕竟不是你开辟的
网上说因为上次结果集没有释放, 所有就delete了,但是有没有delete结果都一样出错.
二班的码农 2015-08-27
  • 打赏
  • 举报
回复
不懂,会不会 delete pReSet1; pReSet1 = NULL; 不需要释放,毕竟不是你开辟的
蜗牛的信仰 2015-08-27
  • 打赏
  • 举报
回复
存储过程里面test() ,只有一条select 语句.
mLee79 2015-08-27
  • 打赏
  • 举报
回复
只用 C , C++里应该也差不多... 获得 存储过程 和 select 的结果是不一样的, 存储过程会同时返回多个 rs, 要一直调用 mysql_next_result , mysql_store_result 直到没有 rs 返回为止 ... 直接调用 select 就只要 mysql_use_result 才能像你那样用...

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧