MySQL 连接器/C++ 1.1 开发人员指南  / 第 7 章连接器/C++ 教程  / 7.2 使用语句对象调用存储过程  /  7.2.2 对返回输出参数的存储过程使用语句

7.2.2Statement对返回输出参数的存储过程使用 a

此示例说明如何处理返回输出参数的存储过程。

  1. 复制教程框架代码:

    $> cp framework.cpp sp_scenario2.cpp
  2. 将以下代码添加到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;
  3. 按照第 7.1 节“先决条件和背景信息” 中的说明编译程序 。

  4. 运行程序:

    $> ./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++ 代码中,对每个过程调用执行类似的顺序:

  1. 执行CALL语句。

  2. 通过执行附加查询来获取输出参数。查询产生一个ResultSet 对象。

  3. 使用while循环检索数据。最简单的方法是在 上使用一个 getString方法 ResultSet,传递要访问的变量的名称。在此示例 _reply中用作变量的占位符,因此用作访问结果字典的正确元素的键。

    尽管用于获取输出参数的查询仅返回一行,但使用 while循环捕获多行非常重要,以避免连接变得不稳定的可能性。