MySQL 连接器/C++ 1.1 开发人员指南 / 第 7 章连接器/C++ 教程 / 7.3 使用 PreparedStatement 对象调用存储过程 /
7.3.2 对返回输出参数的存储过程使用 PreparedStatement
此示例说明如何处理返回输出参数的存储过程。
-
复制教程框架代码:
$> cp framework.cpp ps_scenario2.cpp
-
将以下代码添加到
try
教程框架的块中:vector<string> cont_vector; cont_vector.push_back("Europe"); cont_vector.push_back("North America"); cont_vector.push_back("Oceania"); 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()); std::auto_ptr< sql::PreparedStatement > pstmt; std::auto_ptr< sql::ResultSet > res; pstmt.reset(con->prepareStatement("CALL get_pop_continent(?,@pop)")); for (int i=0; i<3; i++) { pstmt->setString(1,cont_vector[i]); pstmt->execute(); res.reset(pstmt->executeQuery("SELECT @pop AS _population")); while (res->next()) cout << "Population of " << cont_vector[i] << " is " << res->getString("_population") << endl; }
此外,取消
#include <vector>
代码顶部附近的注释,因为向量用于存储示例数据。 按照第 7.1 节“先决条件和背景信息” 中的说明编译程序 。
-
运行程序:
$> ./ps_scenario2 Connector/C++ tutorial framework... Population of Europe is 730074600 Population of North America is 482993000 Population of Oceania is 30401150 Done.
在这种情况下PreparedStatement
,将创建一个调用get_pop_continent
存储过程的对象。此过程接受一个输入参数,并返回一个输出参数。使用的方法是创建另一个语句,该语句可用于使用SELECT
查询获取输出参数。请注意,
PreparedStatement
创建 时,存储过程的输入参数由“?”表示。在执行准备好的语句之前,有必要用实际值替换此占位符。这是使用以下
setString
方法完成的:
pstmt->setString(1,cont_vector[i]);
尽管用于获取输出参数的查询仅返回一行,但使用
while
循环捕获多行非常重要,以避免连接变得不稳定的可能性。