MySQL 连接器/C++ 1.1 开发人员指南 / 第 7 章连接器/C++ 教程 / 7.3 使用 PreparedStatement 对象调用存储过程 /
7.3.1 对不返回结果的存储过程使用 PreparedStatement
此示例说明如何调用不返回结果集的存储过程。
-
复制教程框架代码:
$> cp framework.cpp ps_scenario1.cpp
-
将以下代码添加到
try
教程框架的块中:vector<string> code_vector; code_vector.push_back("SLD"); code_vector.push_back("DSN"); code_vector.push_back("ATL"); vector<string> name_vector; name_vector.push_back("Sealand"); name_vector.push_back("Disneyland"); name_vector.push_back("Atlantis"); 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::PreparedStatement > pstmt; pstmt.reset(con->prepareStatement("CALL add_country(?,?,?)")); for (int i=0; i<3; i++) { pstmt->setString(1,code_vector[i]); pstmt->setString(2,name_vector[i]); pstmt->setString(3,cont_vector[i]); pstmt->execute(); }
此外,取消
#include <vector>
代码顶部附近的注释,因为向量用于存储示例数据。 按照第 7.1 节“先决条件和背景信息” 中的说明编译程序 。
-
运行程序:
$> ./ps_scenario1
-
您可以使用以下查询检查数据库是否已正确更新:
mysql> SELECT Code, Name, Continent FROM Country -> WHERE Code IN('DSN','ATL','SLD'); +------+------------+---------------+ | Code | Name | Continent | +------+------------+---------------+ | ATL | Atlantis | Oceania | | DSN | Disneyland | North America | | SLD | Sealand | Europe | +------+------------+---------------+
代码相对简单,因为不需要处理结果集。过程调用CALL
add_country(?,?,?)
是使用由 表示的输入参数的占位符进行的'?'
。PreparedStatement
这些占位符被使用对象的
方法替换为适当的数据值setString
。for
循环设置为迭代 3 次,因为本例中有三个数据集。同样PreparedStatement
的操作执行了三次,每次都使用不同的输入参数。