MySQL Connector/C++ 1.1 Developer Guide
This example shows how to handle result sets produced by a stored procedure.
Make a copy of the tutorial framework code:
shell> cp framework.cpp sp_scenario3.cpp
Add the following code to the try
block
of the tutorial framework:
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());
Compile the program as described in Section 7.1, “Prerequisites and Background Information”.
Run the program:
shell> ./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.
The code is similar to the examples shown previously. The code of particular interest here is:
do { res.reset(stmt->getResultSet()); while (res->next()) { cout << "Name: " << res->getString("Name") << " Population: " << res->getInt("Population") << endl; } } while (stmt->getMoreResults());
The CALL
is executed as before,
but this time the results are returned into multiple
ResultSet
objects because the stored
procedure executes multiple SELECT
statements. In this example, the output shows that three result
sets are processed, because there are three
SELECT
statements in the stored procedure.
Each result set returns more than one row.
The results are processed using this code pattern:
do { Get Result Set while (Get Result) { Process Result } } while (Get More Result Sets);
Use this pattern even if the stored procedure executes only a
single SELECT
and produces only one result
set. This is a requirement of the underlying protocol.