Table of Contents
Source distributions of Connector/C++ include an
examples directory that contains usage examples
that explain how to use the following classes:
Connection
Driver
PreparedStatement
ResultSet
ResultSetMetaData
Statement
The examples cover:
Using the Driver class to connect to
MySQL
Creating tables, inserting rows, fetching rows using (simple) statements
Creating tables, inserting rows, fetching rows using prepared statements
Hints for working around prepared statement limitations
Accessing result set metadata
Several examples in this document are only code snippets, not
complete programs. These snippets provide a brief overview on the
API. For complete programs, check the examples
directory of your Connector/C++ installation Please also read the
README file in that directory. To test the
example code, edit the examples.h file in the
examples directory to add your connection
information, then rebuild the code by issuing a
make command.
The example programs in the examples directory
include:
connect.cpp:
How to create a connection, insert data, and handle exceptions.
connection_meta_schemaobj.cpp:
How to obtain metadata associated with a connection object, such as a list of tables or databases, the MySQL version, or the connector version.
debug_output.cpp:
How to activate and deactivate the Connector/C++ debug protocol.
exceptions.cpp:
A closer look at the exceptions thrown by the connector and how to fetch error information.
prepared_statements.cpp:
How to execute Prepared Statements, including an example showing how to handle SQL statements that cannot be prepared by the MySQL Server.
resultset.cpp:
How to use a cursor to fetch data and iterate over a result set.
resultset_meta.cpp:
How to obtain metadata associated with a result set, such as the number of columns and column types.
resultset_types.cpp:
Result sets returned from metadata methods. (This is more a test than an example.)
standalone_example.cpp:
Simple standalone program not integrated into regular CMake builds.
statements.cpp:
How to execute SQL statements without using Prepared Statements.
cpp_trace_analyzer.cpp:
This example shows how to filter the output of the debug trace. Please see the inline comments for further documentation. This script is unsupported.
To establish a connection to 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.
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
To run simple queries, you can use the
sql::Statement::execute(),
sql::Statement::executeQuery(), and
sql::Statement::executeUpdate() methods.
Use the method sql::Statement::execute()
if your query does not return a result set or if your query
returns more than one result set. See the
examples directory for more information.
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "user", "password");
stmt = con->createStatement();
stmt->execute("USE " EXAMPLE_DB);
stmt->execute("DROP TABLE IF EXISTS test");
stmt->execute("CREATE TABLE test(id INT, label CHAR(1))");
stmt->execute("INSERT INTO test(id, label) VALUES (1, 'a')");
delete stmt;
delete con;
You must free the sql::Statement and
sql::Connection objects explicitly using
delete.
The API for fetching result sets is identical for (simple)
statements and prepared statements. If your query returns one
result set, use
sql::Statement::executeQuery() or
sql::PreparedStatement::executeQuery() to
run your query. Both methods return
sql::ResultSet objects. By default, Connector/C++
buffers all result sets on the client to support cursors.
// ...
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
// ...
stmt = con->createStatement();
// ...
res = stmt->executeQuery("SELECT id, label FROM test ORDER BY id ASC");
while (res->next()) {
// You can use either numeric offsets...
cout << "id = " << res->getInt(1); // getInt(1) returns the first column
// ... or column names for accessing results.
// The latter is recommended.
cout << ", label = '" << res->getString("label") << "'" << endl;
}
delete res;
delete stmt;
delete con;
In the preceding code snippet, column indexing starts from 1.
You must free the sql::Statement,
sql::Connection, and
sql::ResultSet objects explicitly using
delete.
Cursor usage is demonstrated in the examples contained in the download package.
If you are not familiar with Prepared Statements in MySQL, take a
look at the source code comments and explanations in the file
examples/prepared_statement.cpp.
sql::PreparedStatement is created by
passing an SQL query to
sql::Connection::prepareStatement(). As
sql::PreparedStatement is derived from
sql::Statement, you will feel familiar with
the API once you have learned how to use (simple) statements
(sql::Statement). For example, the syntax
for fetching results is identical.
// ...
sql::Connection *con;
sql::PreparedStatement *prep_stmt
// ...
prep_stmt = con->prepareStatement("INSERT INTO test(id, label) VALUES (?, ?)");
prep_stmt->setInt(1, 1);
prep_stmt->setString(2, "a");
prep_stmt->execute();
prep_stmt->setInt(1, 2);
prep_stmt->setString(2, "b");
prep_stmt->execute();
delete prep_stmt;
delete con;
You must free the sql::PreparedStatement
and sql::Connection objects explicitly
using delete.
The following code shows a complete example of how to use Connector/C++.
/* Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-C++ in the directory of this
software distribution.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
The following code shows a complete example of how to use Connector/C++.
/* Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
There are special exceptions to the terms and conditions of the GPL
as it is applied to this software. View the full text of the
exception in file EXCEPTIONS-CONNECTOR-C++ in the directory of this
software distribution.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#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>
using namespace std;
int main(void)
{
cout << endl;
cout << "Let's have MySQL count from 10 to 1..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
sql::PreparedStatement *pstmt;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
stmt->execute("DROP TABLE IF EXISTS test");
stmt->execute("CREATE TABLE test(id INT)");
delete stmt;
/* '?' is the supported placeholder syntax */
pstmt = con->prepareStatement("INSERT INTO test(id) VALUES (?)");
for (int i = 1; i <= 10; i++) {
pstmt->setInt(1, i);
pstmt->executeUpdate();
}
delete pstmt;
/* Select in ascending order */
pstmt = con->prepareStatement("SELECT id FROM test ORDER BY id ASC");
res = pstmt->executeQuery();
/* Fetch in reverse = descending order! */
res->afterLast();
while (res->previous())
cout << "\t... MySQL counts: " << res->getInt("id") << endl;
delete res;
delete pstmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << »
" )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}