10bet网址
MySQL Connector/C++ 1.1 Developer Guide
Related Documentation Download this Manual
PDF (US Ltr)- 285.1Kb
PDF (A4)- 286.0Kb


MySQL Connector/C++ 1.1 Developer Guide/.../ Using a Statement for a Stored Procedure That Returns an Output Parameter

7.2.2 Using aStatementfor a Stored Procedure That Returns an Output Parameter

This example shows how to handle a stored procedure that returns an output parameter.

  1. Make a copy of the tutorial framework code:

    $> cp framework.cpp sp_scenario2.cpp
  2. Add the following code to thetryblock of the tutorial framework:

    sql::Driver* driver = get_driver_instance(); std::auto_ptr con(driver->connect(url, user, pass)); con->setSchema(database); std::auto_ptr stmt(con->createStatement()); stmt->execute("CALL get_pop('Uganda', @pop)"); std::auto_ptr 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. Compile the program as described inSection 7.1, “Prerequisites and Background Information”.

  4. Run the program:

    $> ./sp_scenario2 Connector/C++ tutorial framework... Population of Uganda: 21778000 Population of Asia: 3705025700 Population of World: 6078749450 Done.

In this scenario, each stored procedure sets the value of an output parameter. This is not returned directly to theexecutemethod, but needs to be obtained using a subsequent query. If you were executing the SQL statements directly, you might use statements similar to these:

CALL get_pop('Uganda', @pop); SELECT @pop; CALL get_pop_continent('Asia', @pop); SELECT @pop; CALL get_pop_world(@pop); SELECT @pop;

In the C++ code, a similar sequence is carried out for each procedure call:

  1. Execute theCALLstatement.

  2. 通过执行一个additi获得输出参数onal query. The query produces aResultSetobject.

  3. Retrieve the data using awhileloop. The simplest way to do this is to use agetStringmethod on theResultSet, passing the name of the variable to access. In this example_replyis used as a placeholder for the variable and therefore is used as the key to access the correct element of the result dictionary.

    Although the query used to obtain the output parameter returns only a single row, it is important to use thewhileloop to catch more than one row, to avoid the possibility of the connection becoming unstable.