[+/-]
Here are some tutorials on using MySQL Connector/C++. Also consult the examples in Section 21.4.5, “MySQL Connector/C++ Getting Started: Usage Examples”.
Setting up the World database for use in the tutorials
These tutorials refer to tables and sample data from the
World
database, which you can download from the
MySQL
Documentation page. Look for the section called
“Example Databases”.
Tutorial framework code
These examples all use the following framework, to avoid repeating code:
#include <stdlib.h> #include <iostream> #include <sstream> #include <stdexcept> #include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #define EXAMPLE_HOST "localhost" #define EXAMPLE_USER "root" #define EXAMPLE_PASS "" #define EXAMPLE_DB "world" using namespace std; int main(int argc, const char **argv) { string url(argc >= 2 ? argv[1] : EXAMPLE_HOST); const string user(argc >= 3 ? argv[2] : EXAMPLE_USER); const string pass(argc >= 4 ? argv[3] : EXAMPLE_PASS); const string database(argc >= 5 ? argv[4] : EXAMPLE_DB); cout << "Connector/C++ tutorial framework..." << endl; cout << endl; try { /* INSERT TUTORIAL CODE HERE! */ } 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() (derived from std::runtime_error) to fetch the error message */ cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; return EXIT_FAILURE; } cout << "Done." << endl; return EXIT_SUCCESS; }
To compile and run the framework
First, copy and paste the framework code to a file such as
frmwk.cpp
. Edit the #define
statements to reflect your connection details (server, user,
password, database).
To compile the framework, for example on Mac OS X, type:
shell> g++ -o frmwk -I/usr/local/include -I/usr/local/include/cppconn -lmysqlcppconn frmwk.cpp
To run the framework, enter the following:
shell> ./frmwk
You will see a simple message. You are now ready to continue to the tutorials.
User Comments
Add your own comment.