Documentation Home
MySQL Connector/C++ Developer Guide
Related Documentation Download this Manual
PDF (US Ltr) - 249.2Kb
PDF (A4) - 252.8Kb
HTML Download (TGZ) - 52.5Kb
HTML Download (Zip) - 66.8Kb


6.1 Connecting to MySQL

To establish a connection to the MySQL server, retrieve an instance of sql::Connection from a sql::mysql::MySQL_Driver object. A sql::mysql::MySQL_Driver object is returned by sql::mysql::get_mysql_driver_instance().

sql::mysql::MySQL_Driver *driver;
sql::Connection *con;

driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "user", "password");

delete con;

Make sure that you free con, the sql::Connection object, as soon as you do not need it any more. But do not explicitly free driver, the connector object. Connector/C++ takes care of freeing that.

Note

get_mysql_driver_instance() calls get_driver_instance(), which is not thread-safe. Either avoid invoking these methods from within multiple threads at once, or surround the calls with a mutex to prevent simultaneous execution in multiple threads.

These methods can be used to check the connection state or reconnect:

  • sql::Connection::isValid() checks whether the connection is alive

  • sql::Connection::reconnect() reconnects if the connection has gone down

For more information about connection options, see Chapter 10, Connector/C++ Connection Options.


User Comments
User comments in this section are, as the name implies, provided by MySQL users. The MySQL documentation team is not responsible for, nor do they endorse, any of the information provided here.
Sign Up Login You must be logged in to post a comment.