Advertisement
Guest User

Untitled

a guest
Nov 12th, 2012
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <memory>
  4. #include <string>
  5. #include <stdexcept>
  6.  
  7. /* MySQL Connector/C++ specific headers */
  8. #include <driver.h>
  9. #include <connection.h>
  10. #include <statement.h>
  11. #include <prepared_statement.h>
  12. #include <resultset.h>
  13. #include <metadata.h>
  14. #include <resultset_metadata.h>
  15. #include <exception.h>
  16. #include <warning.h>
  17.    
  18. #define DBHOST "tcp://127.0.0.1:3306"
  19. #define USER "root"
  20. #define PASSWORD "admin"
  21. #define DATABASE "test"
  22.  
  23. #define NUMOFFSET 100
  24. #define COLNAME 200
  25. #define EXIT_FAILURE 1
  26. #define EXIT_SUCCESS 0
  27.  
  28. using namespace std;
  29. using namespace sql;
  30.  
  31. static void retrieve_data_and_print (ResultSet *rs, int type, int colidx, string colname) {
  32.  
  33.     /* retrieve the row count in the result set */
  34.     cout << "\nRetrieved " << rs -> rowsCount() << " row(s)." << endl;
  35.  
  36.     cout << "\nCityName" << endl;
  37.     cout << "--------" << endl;
  38.  
  39.     /* fetch the data : retrieve all the rows in the result set */
  40.     while (rs->next()) {
  41.         if (type == NUMOFFSET) {
  42.                        cout << rs -> getString(colidx) << endl;
  43.         } else if (type == COLNAME) {
  44.                        cout << rs -> getString(colname) << endl;
  45.         } // if-else
  46.     } // while
  47.  
  48.     cout << endl;
  49.  
  50. } // retrieve_data_and_print()
  51.  
  52. static void retrieve_dbmetadata_and_print (Connection *dbcon) {
  53.  
  54.     if (dbcon -> isClosed()) {
  55.         throw runtime_error("DatabaseMetaData FAILURE - database connection closed");
  56.     }
  57.  
  58.     cout << "\nDatabase Metadata" << endl;
  59.     cout << "-----------------" << endl;
  60.  
  61.     cout << boolalpha;
  62.  
  63.     /* The following commented statement won't work with Connector/C++ 1.0.5 and later */
  64.     //auto_ptr < DatabaseMetaData > dbcon_meta (dbcon -> getMetaData());
  65.  
  66.     DatabaseMetaData *dbcon_meta = dbcon -> getMetaData();
  67.  
  68.     cout << "Database Product Name: " << dbcon_meta -> getDatabaseProductName() << endl;
  69.     cout << "Database Product Version: " << dbcon_meta -> getDatabaseProductVersion() << endl;
  70.     cout << "Database User Name: " << dbcon_meta -> getUserName() << endl << endl;
  71.  
  72.     cout << "Driver name: " << dbcon_meta -> getDriverName() << endl;
  73.     cout << "Driver version: " << dbcon_meta -> getDriverVersion() << endl << endl;
  74.  
  75.     cout << "Database in Read-Only Mode?: " << dbcon_meta -> isReadOnly() << endl;
  76.     cout << "Supports Transactions?: " << dbcon_meta -> supportsTransactions() << endl;
  77.     cout << "Supports DML Transactions only?: " << dbcon_meta -> supportsDataManipulationTransactionsOnly() << endl;
  78.     cout << "Supports Batch Updates?: " << dbcon_meta -> supportsBatchUpdates() << endl;
  79.     cout << "Supports Outer Joins?: " << dbcon_meta -> supportsOuterJoins() << endl;
  80.     cout << "Supports Multiple Transactions?: " << dbcon_meta -> supportsMultipleTransactions() << endl;
  81.     cout << "Supports Named Parameters?: " << dbcon_meta -> supportsNamedParameters() << endl;
  82.     cout << "Supports Statement Pooling?: " << dbcon_meta -> supportsStatementPooling() << endl;
  83.     cout << "Supports Stored Procedures?: " << dbcon_meta -> supportsStoredProcedures() << endl;
  84.     cout << "Supports Union?: " << dbcon_meta -> supportsUnion() << endl << endl;
  85.  
  86.     cout << "Maximum Connections: " << dbcon_meta -> getMaxConnections() << endl;
  87.     cout << "Maximum Columns per Table: " << dbcon_meta -> getMaxColumnsInTable() << endl;
  88.     cout << "Maximum Columns per Index: " << dbcon_meta -> getMaxColumnsInIndex() << endl;
  89.     cout << "Maximum Row Size per Table: " << dbcon_meta -> getMaxRowSize() << " bytes" << endl;
  90.  
  91.     cout << "\nDatabase schemas: " << endl;
  92.  
  93.     auto_ptr < ResultSet > rs ( dbcon_meta -> getSchemas());
  94.  
  95.     cout << "\nTotal number of schemas = " << rs -> rowsCount() << endl;
  96.     cout << endl;
  97.  
  98.     int row = 1;
  99.  
  100.     while (rs -> next()) {
  101.         cout << "\t" << row << ". " << rs -> getString("TABLE_SCHEM") << endl;
  102.         ++row;
  103.     } // while
  104.  
  105.     cout << endl << endl;
  106.  
  107. } // retrieve_dbmetadata_and_print()
  108.  
  109. static void retrieve_rsmetadata_and_print (ResultSet *rs) {
  110.  
  111.     if (rs -> rowsCount() == 0) {
  112.         throw runtime_error("ResultSetMetaData FAILURE - no records in the result set");
  113.     }
  114.  
  115.     cout << "ResultSet Metadata" << endl;
  116.     cout << "------------------" << endl;
  117.  
  118.     /* The following commented statement won't work with Connector/C++ 1.0.5 and later */
  119.     //auto_ptr < ResultSetMetaData > res_meta ( rs -> getMetaData() );
  120.  
  121.     ResultSetMetaData *res_meta = rs -> getMetaData();
  122.  
  123.     int numcols = res_meta -> getColumnCount();
  124.     cout << "\nNumber of columns in the result set = " << numcols << endl << endl;
  125.  
  126.     cout.width(20);
  127.     cout << "Column Name/Label";
  128.     cout.width(20);
  129.     cout << "Column Type";
  130.     cout.width(20);
  131.     cout << "Column Size" << endl;
  132.  
  133.     for (int i = 0; i < numcols; ++i) {
  134.         cout.width(20);
  135.         cout << res_meta -> getColumnLabel (i+1);
  136.         cout.width(20);
  137.         cout << res_meta -> getColumnTypeName (i+1);
  138.         cout.width(20);
  139.         cout << res_meta -> getColumnDisplaySize (i+1) << endl << endl;
  140.     }
  141.  
  142.     cout << "\nColumn \"" << res_meta -> getColumnLabel(1);
  143.     cout << "\" belongs to the Table: \"" << res_meta -> getTableName(1);
  144.     cout << "\" which belongs to the Schema: \"" << res_meta -> getSchemaName(1) << "\"" << endl << endl;
  145.  
  146. } // retrieve_rsmetadata_and_print()
  147.  
  148.  
  149. int main(int argc, const char *argv[]) {
  150.  
  151.     Driver *driver;
  152.     Connection *con;
  153.     Statement *stmt;
  154.     ResultSet *res;
  155.     PreparedStatement *prep_stmt;
  156.     Savepoint *savept;
  157.  
  158.     int updatecount = 0;
  159.  
  160.     /* initiate url, user, password and database variables */
  161.     string url(argc >= 2 ? argv[1] : DBHOST);
  162.     const string user(argc >= 3 ? argv[2] : USER);
  163.     const string password(argc >= 4 ? argv[3] : PASSWORD);
  164.     const string database(argc >= 5 ? argv[4] : DATABASE);
  165.  
  166.     try {
  167.         driver = get_driver_instance();
  168.        
  169.         /* create a database connection using the Driver */
  170.         con = driver -> connect(url, user, password);
  171.  
  172.         /* alternate syntax using auto_ptr to create the db connection */
  173.         //auto_ptr  con (driver -> connect(url, user, password));
  174.  
  175.         /* turn off the autocommit */
  176.         con -> setAutoCommit(0);
  177.  
  178.         cout << "\nDatabase connection\'s autocommit mode = " << con -> getAutoCommit() << endl;
  179.  
  180.         /* select appropriate database schema */
  181.         con -> setSchema(database);
  182.  
  183.         /* retrieve and display the database metadata */
  184.         retrieve_dbmetadata_and_print (con);
  185.  
  186.         /* create a statement object */
  187.         stmt = con -> createStatement();
  188.  
  189.         cout << "Executing the Query: \"SELECT * FROM City\" .." << endl;
  190.  
  191.         /* run a query which returns exactly one result set */
  192.         res = stmt -> executeQuery ("SELECT * FROM City");
  193.  
  194.         cout << "Retrieving the result set .." << endl;
  195.  
  196.         /* retrieve the data from the result set and display on stdout */
  197.         retrieve_data_and_print (res, NUMOFFSET, 1, string("CityName"));
  198.  
  199.         /* retrieve and display the result set metadata */
  200.         retrieve_rsmetadata_and_print (res);
  201.  
  202.         cout << "Demonstrating Prepared Statements .. " << endl << endl;
  203.  
  204.         /* insert couple of rows of data into City table using Prepared Statements */
  205.         prep_stmt = con -> prepareStatement ("INSERT INTO City (CityName) VALUES (?)");
  206.  
  207.         cout << "\tInserting \"London, UK\" into the table, City .." << endl;
  208.  
  209.         prep_stmt -> setString (1, "London, UK");
  210.         updatecount = prep_stmt -> executeUpdate();
  211.  
  212.         cout << "\tCreating a save point \"SAVEPT1\" .." << endl;
  213.         savept = con -> setSavepoint ("SAVEPT1");
  214.  
  215.         cout << "\tInserting \"Paris, France\" into the table, City .." << endl;
  216.  
  217.         prep_stmt -> setString (1, "Paris, France");
  218.         updatecount = prep_stmt -> executeUpdate();
  219.  
  220.         cout << "\tRolling back until the last save point \"SAVEPT1\" .." << endl;
  221.         con -> rollback (savept);
  222.         con -> releaseSavepoint (savept);
  223.  
  224.         cout << "\tCommitting outstanding updates to the database .." << endl;
  225.         con -> commit();
  226.  
  227.         cout << "\nQuerying the City table again .." << endl;
  228.  
  229.         /* re-use result set object */
  230.         res = NULL;
  231.         res = stmt -> executeQuery ("SELECT * FROM City");
  232.  
  233.         /* retrieve the data from the result set and display on stdout */
  234.         retrieve_data_and_print (res, COLNAME, 1, string ("CityName"));
  235.  
  236.         cout << "Cleaning up the resources .." << endl;
  237.  
  238.         /* Clean up */
  239.         delete res;
  240.         delete stmt;
  241.         delete prep_stmt;
  242.         con -> close();
  243.         delete con;
  244.  
  245.     } catch (SQLException &e) {
  246.         cout << "ERROR: SQLException in " << __FILE__;
  247.         cout << " (" << __func__<< ") on line " << __LINE__ << endl;
  248.         cout << "ERROR: " << e.what();
  249.         cout << " (MySQL error code: " << e.getErrorCode();
  250.         cout << ", SQLState: " << e.getSQLState() << ")" << endl;
  251.  
  252.         if (e.getErrorCode() == 1047) {
  253.             /*
  254.             Error: 1047 SQLSTATE: 08S01 (ER_UNKNOWN_COM_ERROR)
  255.             Message: Unknown command
  256.             */
  257.             cout << "\nYour server does not seem to support Prepared Statements at all. ";
  258.             cout << "Perhaps MYSQL < 4.1?" << endl;
  259.         }
  260.  
  261.         return EXIT_FAILURE;
  262.     } catch (std::runtime_error &e) {
  263.  
  264.         cout << "ERROR: runtime_error in " << __FILE__;
  265.         cout << " (" << __func__ << ") on line " << __LINE__ << endl;
  266.         cout << "ERROR: " << e.what() << endl;
  267.  
  268.         return EXIT_FAILURE;
  269.     }
  270.  
  271.     return EXIT_SUCCESS;
  272. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement