Advertisement
Guest User

Untitled

a guest
Aug 1st, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <memory>
  4. #include <mysql_driver.h>
  5. #include <mysql_connection.h>
  6. #include <mysql_error.h>
  7. #include <cppconn/Statement.h>
  8. #include <cppconn/ResultSet.h>
  9.  
  10. //define your own configurations in "mysql_config.hpp"
  11. //for example: HOST = "tcp://127.0.0.1:3306", DATABASE = "database_name"
  12. #include "mysql_config.hpp"
  13. using namespace std;
  14.  
  15. int main()
  16. {
  17. stringstream sql_statement;
  18.  
  19. try {
  20. sql::mysql::MySQL_Driver *driver = sql::mysql::get_mysql_driver_instance();
  21. unique_ptr<sql::Connection> con(driver->connect(HOST, USER, PASSWORD));
  22. unique_ptr<sql::Statement> stmt(con->createStatement());
  23.  
  24.  
  25. stmt->execute("USE " + DATABASE);
  26. stmt->execute("DROP TABLE IF EXISTS conference");
  27. stmt->execute("CREATE TABLE conference(cid int, name varchar(10))");
  28. cout << "test table created." << endl;
  29.  
  30. stmt->execute("INSERT INTO conference VALUES(1, 'SIGMOD')");
  31. stmt->execute("INSERT INTO conference VALUES(2, 'VLDB')");
  32. stmt->execute("INSERT INTO conference VALUES(3, 'ICDE')");
  33. stmt->execute("INSERT INTO conference VALUES(4, 'KDD')");
  34.  
  35. unique_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT * FROM conference"));
  36.  
  37. size_t row = 0;
  38. while (res->next()) {
  39. cout << row << "\t";
  40. /* You can use either numeric offsets... */
  41. cout << "cid = " << res->getInt(1);
  42. /* ... or column names for accessing results. The latter is recommended. */
  43. cout << ", name = '" << res->getString("name") << "' " << endl;
  44. row++;
  45. }
  46.  
  47. } catch (sql::SQLException &e) {
  48. cout << "# ERR: SQLException in " << __FILE__ << " on line " << __LINE__ << endl;
  49. cout << "# ERR: " << e.what() << endl;
  50. cout << " (MySQL error code: " << e.getErrorCode();
  51. cout << ", SQLState: " << e.getSQLState() << " )" << endl;
  52. return EXIT_FAILURE;
  53. } catch (runtime_error &e) {
  54. cout << "# ERR: runtime_error in " << __FILE__ << " on line " << __LINE__ << endl;
  55. cout << "# ERR: " << e.what() << endl;
  56. return EXIT_FAILURE;
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement