1 | // http://dev.mysql.com/doc/refman/5.5/en/connector-cpp-examples-complete-example-2.html |
---|
2 | // g++ -Wall -g twee.cpp -lmysqlcppconn |
---|
3 | #include <stdlib.h> |
---|
4 | #include <iostream> |
---|
5 | |
---|
6 | /* |
---|
7 | Include directly the different |
---|
8 | headers from cppconn/ and mysql_driver.h + mysql_util.h |
---|
9 | (and mysql_connection.h). This will reduce your build time! |
---|
10 | */ |
---|
11 | #include "mysql_connection.h" |
---|
12 | |
---|
13 | #include <cppconn/driver.h> |
---|
14 | #include <cppconn/exception.h> |
---|
15 | #include <cppconn/resultset.h> |
---|
16 | #include <cppconn/statement.h> |
---|
17 | #include <cppconn/prepared_statement.h> |
---|
18 | |
---|
19 | using namespace std; |
---|
20 | |
---|
21 | int main(void) |
---|
22 | { |
---|
23 | cout << endl; |
---|
24 | cout << "Let's have MySQL count from 10 to 1..." << endl; |
---|
25 | |
---|
26 | try { |
---|
27 | sql::Driver *driver; |
---|
28 | sql::Connection *con; |
---|
29 | sql::Statement *stmt; |
---|
30 | sql::ResultSet *res; |
---|
31 | sql::PreparedStatement *pstmt; |
---|
32 | |
---|
33 | /* Create a connection */ |
---|
34 | driver = get_driver_instance(); |
---|
35 | con = driver->connect("tcp://127.0.0.1:3307", "stopos", "x"); |
---|
36 | /* Connect to the MySQL test database */ |
---|
37 | con->setSchema("stopos"); |
---|
38 | |
---|
39 | stmt = con->createStatement(); |
---|
40 | stmt->execute("DROP TABLE IF EXISTS test"); |
---|
41 | stmt->execute("CREATE TABLE test(id INT)"); |
---|
42 | delete stmt; |
---|
43 | |
---|
44 | /* '?' is the supported placeholder syntax */ |
---|
45 | pstmt = con->prepareStatement("INSERT INTO test(id) VALUES (?)"); |
---|
46 | for (int i = 1; i <= 10; i++) { |
---|
47 | pstmt->setInt(1, i); |
---|
48 | pstmt->executeUpdate(); |
---|
49 | } |
---|
50 | delete pstmt; |
---|
51 | |
---|
52 | /* Select in ascending order */ |
---|
53 | pstmt = con->prepareStatement("SELECT id FROM test ORDER BY id ASC"); |
---|
54 | res = pstmt->executeQuery(); |
---|
55 | |
---|
56 | /* Fetch in reverse = descending order! */ |
---|
57 | res->afterLast(); |
---|
58 | while (res->previous()) |
---|
59 | cout << "\t... MySQL counts: " << res->getInt("id") << endl; |
---|
60 | delete res; |
---|
61 | |
---|
62 | delete pstmt; |
---|
63 | delete con; |
---|
64 | |
---|
65 | } catch (sql::SQLException &e) { |
---|
66 | cout << "# ERR: SQLException in " << __FILE__; |
---|
67 | cout << "(" << __FUNCTION__ << ") on line " |
---|
68 | << __LINE__ << endl; |
---|
69 | cout << "# ERR: " << e.what(); |
---|
70 | cout << " (MySQL error code: " << e.getErrorCode(); |
---|
71 | cout << ", SQLState: " << e.getSQLState() << |
---|
72 | " )" << endl; |
---|
73 | } |
---|
74 | |
---|
75 | cout << endl; |
---|
76 | |
---|
77 | return EXIT_SUCCESS; |
---|
78 | } |
---|