/* Copyright 2007 - 2008 MySQL AB, 2008 - 2009 Sun Microsystems, Inc. All rights reserved. The MySQL Connector/C++ is licensed under the terms of the GPL , like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPL as it is applied to this software, see the FLOSS License Exception . */ /* * * Basic example demonstrating scrolling through a result set * */ /* Standard C++ includes */ #include #include #include #include /* Public interface of the MySQL Connector/C++ */ #include /* Connection parameter and sample data */ #include "examples.h" static void validateResultSet(std::auto_ptr< sql::ResultSet > & res, struct _test_data *min, struct _test_data *max); using namespace std; int main(int argc, const char **argv) { static const string url(argc >= 2 ? argv[1] : EXAMPLE_HOST); static const string user(argc >= 3 ? argv[2] : EXAMPLE_USER); static const string pass(argc >= 4 ? argv[3] : EXAMPLE_PASS); static const string database(argc >= 5 ? argv[4] : EXAMPLE_DB); /* Driver Manager */ sql::Driver *driver; /* sql::ResultSet.rowsCount() returns size_t */ stringstream sql; int i; struct _test_data min, max; string dateStr; //* 8/26/10 - SCA cout << boolalpha; cout << "1..1" << endl; cout << "# Connector/C++ result set.." << endl; try { /* Using the Driver to create a connection */ driver = get_driver_instance(); std::auto_ptr< sql::Connection > con(driver->connect(url, user, pass)); con->setSchema(database); /* Creating a "simple" statement - "simple" = not a prepared statement */ std::auto_ptr< sql::Statement > stmt(con->createStatement()); stmt->execute("DROP TABLE IF EXISTS test"); stmt->execute("CREATE TABLE test(id INT, label CHAR(1), myDateTime Datetime)"); //* 8/26/10 - SCA cout << "#\t Test table created" << endl; /* Populate the test table with data */ min = max = test_data[0]; for (i = 0; i < EXAMPLE_NUM_TEST_ROWS; i++) { /* Remember mnin/max values for further testing */ if (test_data[i].id < min.id) { min = test_data[i]; } if (test_data[i].id > max.id) { max = test_data[i]; } /* KLUDGE: You should take measures against SQL injections! */ sql.str(""); sql << "INSERT INTO test(id, label, myDateTime) VALUES ("; //* 8/26/10 - SCA sql << test_data[i].id << ", '" << test_data[i].label << "', '" << dateStr.c_str() << "')"; //* 8/26/10 - SCA stmt->execute(sql.str()); } cout << "#\t Test table populated" << endl; dateStr = "2010-06-19 20:58:00"; //* 8/26/10 - SCA /* This is an example how to fetch in reverse order using the ResultSet cursor. Every ResultSet object maintains a cursor, which points to its current row of data. The cursor is 1-based. The first row has the cursor position 1. NOTE: The Connector/C++ preview/alpha uses buffered results. THe driver will always fetch all data no matter how big the result set is! */ cout << "#\t Testing sql::Statement based resultset" << endl; { std::auto_ptr< sql::ResultSet > res(stmt->executeQuery("SELECT id, label, myDateTime FROM test ORDER BY id ASC")); //* 8/26/10 - SCA validateResultSet(res, &min, &max); } cout << "#" << endl; cout << "#\t Testing sql::PreparedStatment based resultset" << endl; { std::auto_ptr< sql::PreparedStatement > prep_stmt(con->prepareStatement("SELECT id, label FROM test ORDER BY id ASC")); //* 8/26/10 S. Abraham Commented out the line that executes the //* prepared statement query, because it failed with an error. //* 8/26/10 - SCA *std::auto_ptr< sql::ResultSet > res(prep_stmt->executeQuery()); //* 8/26/10 - SCA *validateResultSet(res, &min, &max); } /* Clean up */ stmt->execute("DROP TABLE IF EXISTS test"); cout << "# done!" << endl; } catch (sql::SQLException &e) { /* The MySQL Connector/C++ throws three different exceptions: - sql::MethodNotImplementedException (derived from sql::SQLException) - sql::InvalidArgumentException (derived from sql::SQLException) - sql::SQLException (derived from std::runtime_error) */ cout << "# ERR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; // Use what(), getErrorCode() and getSQLState() cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; cout << "not ok 1 - examples/resultset.cpp" << endl; return EXIT_FAILURE; } catch (std::runtime_error &e) { cout << "# ERR: runtime_error in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; cout << "# ERR: " << e.what() << endl; cout << "not ok 1 - examples/resultset.cpp" << endl; return EXIT_FAILURE; } cout << "ok 1 - examples/resultset.cpp" << endl; return EXIT_SUCCESS; } //*** END - Main() *** static void validateRow(std::auto_ptr< sql::ResultSet > & res, struct _test_data *exp) { stringstream msg; cout << "#\t\t Fetching the first row, id = " << res->getInt("id"); cout << ", label = '" << res->getString("label") << "'" << endl; if ((res->getInt("id") != exp->id) || (res->getString("label") != exp->label)) { msg.str("Wrong results"); msg << "Expected (" << exp->id << "," << exp->label << ")"; msg << " got (" << res->getInt("id") <<", " << res->getString("label") << ")"; throw runtime_error(msg.str()); } } //*** END - validateRow() *** static void validateResultSet(std::auto_ptr< sql::ResultSet > & res, struct _test_data *min, struct _test_data *max) { size_t row; string tmpStr; //* 8/26/10 - SCA cout << "#\t Selecting in ascending order but fetching in descending (reverse) order" << endl; /* Move the cursor after the last row - n + 1 */ res->afterLast(); if (true != res->isAfterLast()) throw runtime_error("Position should be after last row (1)"); row = res->rowsCount() - 1; /* Move the cursor backwards to: n, n - 1, ... 1, 0. Return true if rows are available. */ while (res->previous()) { cout << "#\t\t Row " << row << " id = " << res->getInt("id"); cout << ", label = '" << res->getString("label") << "'" << endl; tmpStr = res->getString("myDateTime"); //* 8/26/10 - SCA row--; } } //*** END - validateResultSet() ***