此示例说明如何处理返回输出参数的存储过程。
-
复制教程框架代码:
$> cp framework.cpp sp_scenario2.cpp
-
将以下代码添加到
try
教程框架的块中:sql::Driver* driver = get_driver_instance(); std::auto_ptr<sql::Connection> con(driver->connect(url, user, pass)); con->setSchema(database); std::auto_ptr<sql::Statement> stmt(con->createStatement()); stmt->execute("CALL get_pop('Uganda', @pop)"); std::auto_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT @pop AS _reply")); while (res->next()) cout << "Population of Uganda: " << res->getString("_reply") << endl; stmt->execute("CALL get_pop_continent('Asia', @pop)"); res.reset(stmt->executeQuery("SELECT @pop AS _reply")); while (res->next()) cout << "Population of Asia: " << res->getString("_reply") << endl; stmt->execute("CALL get_pop_world(@pop)"); res.reset(stmt->executeQuery("SELECT @pop AS _reply")); while (res->next()) cout << "Population of World: " << res->getString("_reply") << endl;
按照第 7.1 节“先决条件和背景信息” 中的说明编译程序 。
-
运行程序:
$> ./sp_scenario2 Connector/C++ tutorial framework... Population of Uganda: 21778000 Population of Asia: 3705025700 Population of World: 6078749450 Done.
在这种情况下,每个存储过程都会设置一个输出参数的值。这不会直接返回给
execute
方法,而是需要使用后续查询来获取。如果您直接执行 SQL 语句,您可能会使用类似于以下的语句:
CALL get_pop('Uganda', @pop);
SELECT @pop;
CALL get_pop_continent('Asia', @pop);
SELECT @pop;
CALL get_pop_world(@pop);
SELECT @pop;
在 C++ 代码中,对每个过程调用执行类似的顺序:
执行
CALL
语句。通过执行附加查询来获取输出参数。查询产生一个
ResultSet
对象。-
使用
while
循环检索数据。最简单的方法是在 上使用一个getString
方法ResultSet
,传递要访问的变量的名称。在此示例_reply
中用作变量的占位符,因此用作访问结果字典的正确元素的键。尽管用于获取输出参数的查询仅返回一行,但使用
while
循环捕获多行非常重要,以避免连接变得不稳定的可能性。