7.2.3Statement对返回结果集的存储过程使用 a

此示例说明如何处理存储过程生成的结果集。

  1. 复制教程框架代码:

    $> cp framework.cpp sp_scenario3.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_data()");
    std::auto_ptr< sql::ResultSet > res;
    do {
      res.reset(stmt->getResultSet());
      while (res->next()) {
        cout << "Name: " << res->getString("Name")
             << " Population: " << res->getInt("Population")
             << endl;
      }
    } while (stmt->getMoreResults());
  3. 按照第 7.1 节“先决条件和背景信息” 中的说明编译程序 。

  4. 运行程序:

    $> ./sp_scenario3
    Connector/C++ tutorial framework...
    
    Name: Cocos (Keeling) Islands Population: 600
    Name: Christmas Island Population: 2500
    Name: Norfolk Island Population: 2000
    Name: Niue Population: 2000
    Name: Pitcairn Population: 50
    Name: Tokelau Population: 2000
    Name: United States Minor Outlying Islands Population: 0
    Name: Svalbard and Jan Mayen Population: 3200
    Name: Holy See (Vatican City State) Population: 1000
    Name: Anguilla Population: 8000
    Name: Atlantis Population: 0
    Name: Saint Pierre and Miquelon Population: 7000
    Done.

该代码类似于前面显示的示例。这里特别感兴趣的代码是:

do {
  res.reset(stmt->getResultSet());
  while (res->next()) {
    cout << "Name: " << res->getString("Name")
         << " Population: " << res->getInt("Population")
         << endl;
  }
} while (stmt->getMoreResults());

和之前一样执行,但是这次CALL结果返回到多个 ResultSet对象中,因为存储过程执行了多条SELECT 语句。在这个例子中,输出显示处理了三个结果集,因为 SELECT存储过程中有三个语句。每个结果集返回多行。

使用此代码模式处理结果:

do {
  Get Result Set
  while (Get Result) {
    Process Result
  }
} while (Get More Result Sets);
笔记

即使存储过程只执行一个SELECT并且只产生一个结果集,也可以使用此模式。这是底层协议的要求。