· 8 years ago · Sep 21, 2017, 08:08 PM
1#include <stdlib.h>
2#include <iostream>
3#include <sstream>
4#include <stdexcept>
5#include <cppconn/driver.h>
6#include <cppconn/exception.h>
7#include <cppconn/resultset.h>
8#include <cppconn/statement.h>
9#include <cppconn/prepared_statement.h>
10
11#define EXAMPLE_HOST "localhost"
12#define EXAMPLE_USER "root"
13#define EXAMPLE_PASS "root"
14#define EXAMPLE_DB "cs360"
15
16using namespace std;
17
18int main(int argc, const char **argv) {
19 const string url = EXAMPLE_HOST;
20 const string user = EXAMPLE_USER;
21 const string pass = EXAMPLE_PASS;
22 const string database = EXAMPLE_DB;
23 try {
24 sql::Driver *driver;
25 sql::Connection *con;
26 sql::Statement *stmt;
27 sql::ResultSet *res;
28 sql::PreparedStatement *pstmt;
29
30 /* Create a connection */
31 driver = get_driver_instance();
32 con = driver->connect(url, user, pass);
33 /* Connect to the MySQL test database */
34 con->setSchema(database);
35
36 stmt = con->createStatement();
37 stmt->execute("DROP TABLE IF EXISTS Employee");
38 stmt->execute("CREATE TABLE Employee ("
39 "Id INT NOT NULL AUTO_INCREMENT,"
40 "Name VARCHAR(200),"
41 "Salary INT,"
42 "DepartmentId INT,"
43 "PRIMARY KEY (Id));");
44 delete stmt;
45
46 pstmt = con->prepareStatement("INSERT INTO Employee (Name, Salary, DepartmentId) VALUES (?, ?, ?),(?, ?, ?)");
47 pstmt->setString(1, "Joe");
48 pstmt->setInt(2, 70000);
49 pstmt->setInt(3, 1);
50 pstmt->setString(4, "Henry");
51 pstmt->setInt(5, 80000);
52 pstmt->setInt(6, 2);
53 pstmt->executeUpdate();
54 delete pstmt;
55
56 /* Select in ascending order */
57 pstmt = con->prepareStatement("select * from Employee");
58 res = pstmt->executeQuery();
59
60 /* Fetch in reverse = descending order! */
61 res->afterLast();
62 while (res->previous()) {
63 cout << res->getInt("Id") << " " <<
64 res->getString("Name") << " " <<
65 res->getInt("Salary") << " " <<
66 res->getInt("DepartmentId") << endl;
67 }
68 delete res;
69
70 delete pstmt;
71 delete con;
72
73 } catch (sql::SQLException &e) {
74 cout << "# ERR: SQLException in " << __FILE__;
75 cout << "(" << __FUNCTION__ << ") on line "
76 << __LINE__ << endl;
77 cout << "# ERR: " << e.what();
78 cout << " (MySQL error code: " << e.getErrorCode();
79 cout << ", SQLState: " << e.getSQLState() <<
80 " )" << endl;
81 }
82
83 cout << endl;
84
85 return 0;
86}