MySQL Connector/C++ 9.1.0
MySQL connector library for C and C++ applications
|
Connector/C++ supports the classic C++ API based on the JDBC4 specification. This allows an easy migration to Connector/C++ for applications that use earlier versions of Connector/C++ (e.g., version 1.1). See also MySQL Connector/C++ 1.1 Developer Guide.
The following code demonstrates how to connect to MySQL Server using the classic C++ API. After the connection is established the code executes a simple SQL statement and reads the result from the server. The source file can be found in testapp/jdbc_test.cc in the Connector/C++ source tree. See Using Connector/C++ for instructions on how to build the sample code.
Each program which uses the classic C++ API has to include <mysql/jdbc.h> header:
To establish a connection to MySQL Server, get an instance of sql::Connection
from a sql::Driver
object returned by sql::mysql::get_driver_instance()
:
The connect()
method returns a pointer to a dynamically allocated connection object which is stored in a std::unique_ptr
to ensure that the object is deleted when no longer needed. The same pattern is used for other API methods that return pointers to objects – it is responsibility of the caller to delete them. However, the driver instance should not be explicitly deleted, the connector takes care of freeing it.
get_driver_instance()
function is not thread-safe. Either avoid invoking it 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 alivesql::Connection::reconnect()
reconnects if the connection has gone downWe set the default schema of the connection and create a statement object that will be used to execute a query:
To run simple queries that return a single result set use the sql::Statement::executeQuery()
or sql::PreparedStatement::executeQuery()
method. Both methods return sql::ResultSet
objects. By default the classic API implementation buffers all result sets on the client to support cursors.
sql::Statement::execute()
method instead.The code below walks through the entire result set row by row using sql::ResultSet::next()
method, which returns true
if the row was successfully read. Otherwise it returns false
which means we reached the end of the result set and there are no more rows to read. The actual data is obtained through the getXxxx()
methods getInt()
, getString()
, etc. The columns can be indexed by numbers in the order they are given inside the result set starting from 1. Alternatively the column name can be used as a string index.
Error handling is done using exceptions that derive from sql::SQLException
class that is derived from std::runtime_error
.
Here is the complete C++ code of the test sample for the classic C++ API: