使用 mysql c++ 连接器和以下存储过程(手动工作)
DELIMITER $$
CREATE PROCEDURE sp_getvalues()
BEGIN
SELECT max(a) FROM A;
SELECT max(b1), min(b2) FROM B;
SELECT sum(x) FROM C;
END
$$
DELIMITER ;
DELIMITER $$
以下 C++ 代码给出错误:
Commands out of sync; you can't run this command now
第一次调用stmt->getResultSet()。应该叫什么?
void test_multiple_query(Connection* con) {
sql::Statement* stmt = con->createStatement();
stmt->executeQuery("CALL sp_getvalues()");
sql::ResultSet* res = stmt->getResultSet();
cout << res->getInt(1) << '\n';
delete res;
res = stmt->getResultSet();
cout << res->getInt(1) << '\t' << res->getInt(2) << '\n';
delete res;
res = stmt->getResultSet();
cout << res->getDouble(1)<< '\n';
delete res;
delete stmt;
}
来自 CALL,“如果设置了 CLIENT_MULTI_RESULTS API 标志,CALL 可以返回任意数量的结果集,并且被调用的存储过程可以执行准备好的语句”
在 MariaDB 的 Connector C++ 中,这是通过 property:
完成的connection_properties["CLIENT_MULTI_RESULTS"]= "true";
con.reset(driver->connect(connection_properties));
MySQL文档有示例:
sql::Driver * driver = get_driver_instance();
std::auto_ptr< sql::Connection > con(driver->connect(url, user, pass));
con->setSchema(database);
std::auto_ptr< sql::PreparedStatement > pstmt;
std::auto_ptr< sql::ResultSet > res;
pstmt.reset(con->prepareStatement("CALL get_data()"));
res.reset(pstmt->executeQuery());
for(;;)
{
while (res->next()) {
cout << "Name: " << res->getString("Name")
<< " Population: " << res->getInt("Population")
<< endl;
}
if (pstmt->getMoreResults())
{
res.reset(pstmt->getResultSet());
continue;
}
break;
}