Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
The MariaDB Connector/C++ is used to connect applications developed in C++ to MariaDB and MySQL databases. MariaDB Connector/C++ is LGPLv2.1 licensed.
Quickstart Guide for Connector/C++
MariaDB Connector/C++ enables C++ applications to establish client connections to MariaDB database products over TLS.
C++ applications can connect to MariaDB database products either with MariaDB Connector/C++ or MariaDB Connector/C.
Using MariaDB Connector/C++ in C++ applications enables design with an object-oriented model and enables efficient dynamic memory allocation/de-allocation with smart pointers.
Feature
Connector/C++
Executes SQL
Yes
Yes
Object-Oriented
Yes
No
Smart Pointers
Yes
No
Implements JDBC API
Yes
No
Examples in the MariaDB Connector/C++ documentation depend on a database test and table contacts.
Create a test database if one does not exist with the statement:
Create tables in the test database for testing basic and advanced operations with statements:
Create a user account to test connectivity with the statement:
Ensure that the user account has privileges to access the tables with the statement:
Passwords should meet your organization's password policies. If your MariaDB Enterprise Server instance has a password validation plugin installed, the password must also meet the configured requirements.
By default, MariaDB Enterprise Server installs the simple_password_check plugin, configured with system variables:
system variables.
This page is: Copyright © 2025 MariaDB. All rights reserved.
MariaDB Connector/C++ enables C++ applications to establish client connections to MariaDB database products over TLS.
When you build a C++ application, your compiler must link your application with the MariaDB Connector/C++ shared library.
The following g++ (GNU GCC) command demonstrates how to link an application with the MariaDB Connector/C++ shared library using the -lmariadbcpp argument:
If you are not using the g++ compiler, please consult your compiler's manual.
MariaDB Connector/C++ includes several header files. In some cases, developers might find it useful to inspect the MariaDB Connector/C++ header files to view the definitions of classes, functions, and methods.
The header files:
Contain the definitions of classes, functions, and methods in the sql namespace.
Are installed to the /usr/include/mariadb/conncpp/ directory by default on Linux.
C++ applications developed using MariaDB Connector/C++ must include the conncpp.hpp header file.
When a C++ application includes conncpp.hpp, the application will automatically include other header files that are included by conncpp.hpp:
CallableStatement.hpp
Connection.hpp
DatabaseMetaData.hpp
Driver.hpp
MariaDB Connector/C++ implements many different classes.
Most C++ applications developed using MariaDB Connector/C++ will use some of the following classes:
This page is: Copyright © 2025 MariaDB. All rights reserved.
MariaDB Connector/C++ has dependencies. You must install MariaDB Connector/C to use it.
1.1
3.3.3 or later
For additional information, see "".
To install MariaDB Connector/C++ on Linux:
.
Go to the
Ensure the "Product" dropdown reads "C++ connector."
In the "Version" dropdown, select the version you want to download.
On CentOS, RHEL, Rocky Linux:
On Debian, Ubuntu:
Install the shared libraries:
On CentOS, RHEL, Rocky Linux:
On Debian, Ubuntu:
To install MariaDB Connector/C++ on Windows:
MariaDB Connector/C dependency will be installed when Connector/C++ is installed.
Go to the
Ensure the "Product" dropdown reads "C++ connector."
In the "Version" dropdown, select the version you want to download.
This page is: Copyright © 2025 MariaDB. All rights reserved.
Tasks.cpp is a complete sample application that demonstrates CRUD (Create, Read, Update, Delete) operations using the MariaDB Connector/C++.
The tasks.cpp sample application depends on a database, todo and the table task.,
Create the example database and table:
Create a user db_user with privileges to execute the tasks of the sample application:
Within the tasks.cpp file, navigate to the main method, and add the database connection values:
After adding the connection details to the tasks.cpp file, build the sample application:
The sample application supports CRUD (Create, Read, Update, Delete) operations.
Create a new task record:
Read all task records:
If the task got added, the preceding command lists the task:
Update an existing task record:
If the task got updated, the ./tasks showTasks command lists the updated task:
Delete a task record:
This page is: Copyright © 2025 MariaDB. All rights reserved.
CREATE DATABASE IF NOT EXISTS test;CREATE TABLE test.contacts (
id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(25),
last_name VARCHAR(25),
email VARCHAR(100)) ENGINE=InnoDB;CREATE USER IF NOT EXISTS 'db_user'@'192.0.2.1'
IDENTIFIED BY 'db_user_password';GRANT ALL PRIVILEGES
ON test.*
TO 'db_user'@'192.0.2.1';$ g++ -o example example.cpp -std=c++11 -lmariadbcppCREATE DATABASE IF NOT EXISTS todo;
CREATE TABLE todo. tasks (
id INT AUTO_INCREMENT PRIMARY KEY,
description VARCHAR(200),
completed BOOLEAN DEFAULT FALSE);DriverManager.hpp
Exception.hpp
jdbccompat.hpp
ParameterMetaData.hpp
PreparedStatement.hpp
ResultSet.hpp
ResultSetMetaData.hpp
Savepoint.hpp
SQLString.hpp
Statement.hpp
Types.hpp
Warning.hpp
sql::ResultSetMetaData
Provides detailed information about a result set, such as schema name, table name, column names and types, and column attributes; whether a column is auto increment, and nullable.
sql::Statement
Execute a query that does not contain variable text. A Statement can be closed by calling close(), or there is an implicit close when using a smart pointer.
sql::Connection
Establish a connection to a MariaDB database product. A Connection can be closed by calling close(), or there is an implicit close when using a smart pointer.
sql::DatabaseMetaData
Provides detailed information about the database metadata, such as database name, version, schemas, tables, columns, procedures, and support for various features.
sql::Driver
Implements the non-static connect() method, which is a connection method.
sql::DriverManager
Implements the static getConnection() method, which is a connection method.
sql::PreparedStatement
Execute a query that contains variable text. Prepared statements can be used to sanitize input. Therefore, using prepared statements reduces the risk of SQL injection attacks. A PreparedStatement can be closed by calling close(), or there is an implicit close when using a smart pointer. By default, the connector will use client-side prepared statements. To use server-side prepared statements, set the useServerPrepStmts optional connection parameter to true.
sql::ResultSet
Fetch query results. A ResultSet can be closed by calling close(), or there is an implicit close when using a smart pointer.
Click the "Download" button to download the binary tarball.
Extract the tarball:
Change into the relevant directory:
Install the directories for the header files:
Install the header files:
Install the directories for the shared libraries:
In the "OS" dropdown, select either "MS Windows (64-bit)" or "MS Windows (32-bit)", depending on whether you need a 64-bit or 32-bit connector.
Click the "Download" button to download the MSI package.
Run the MSI package and click "Next" to start the Setup Wizard.
On the second screen, click the license agreement checkbox, then click "Next."
On the third screen, click "Typical."
On the fourth screen, click "Install."
Click "Finish."
Add the directory path that contains the mariadbcpp LIB file (example "C:\Program Files\MariaDB\MariaDB C++ Connector 64-bit") to PATH environment variable.
1.0
3.1.1 or later
$ tar -xvzf mariadb-connector-cpp-*.tar.gz$ cd mariadb-connector-cpp-*/$ sudo install -d /usr/include/mariadb/conncpp
$ sudo install -d /usr/include/mariadb/conncpp/compat$ sudo install include/mariadb/* /usr/include/mariadb/
$ sudo install include/mariadb/conncpp/* /usr/include/mariadb/conncpp
$ sudo install include/mariadb/conncpp/compat/* /usr/include/mariadb/conncpp/compat$ sudo install -d /usr/lib64/mariadb
$ sudo install -d /usr/lib64/mariadb/plugin$ sudo install -d /usr/lib/mariadb
$ sudo install -d /usr/lib/mariadb/plugin$ sudo install lib/mariadb/libmariadbcpp.so /usr/lib64
$ sudo install lib/mariadb/plugin/* /usr/lib64/mariadb/plugin$ sudo install lib/mariadb/libmariadbcpp.so /usr/lib
$ sudo install lib/mariadb/plugin/* /usr/lib/mariadb/pluginCREATE USER IF NOT EXISTS db_user@192.0.2.1
IDENTIFIED BY 'db_user_password';
GRANT ALL PRIVILEGES ON todo.* TO db_user@192.0.2.1;sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/todo");
sql::Properties properties({{"user", "db_user"}, {"password", "db_user_password"}});sql::SQLString url("jdbc:mariadb://example.skysql.net:5509/todo");
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
{"autocommit", false},
{"useTls", true},
{"tlsCert", "classpath:static/skysql_chain.pem"}
});$ g++ -o tasks tasks.cpp -std=c++11 -lmariadbcpp$ ./tasks addTask 'New Task Description'$ ./tasks showTasksid = 1, description = New Task Description, completed = 0$ ./tasks updateTaskStatus 1 1id = 1, description = New Task Description, completed = 1$ ./tasks deleteTask 1C++ developers can use MariaDB Connector/C++ to perform basic DDL (Data Definition Language) operations with MariaDB database products.
DDL (Data Definition Language) refers to all SQL-schema statements in the SQL standard (ISO/IEC 9075-2:2016).
Some examples of DDL include , , , , and .
is a DDL (Data Definition Language) operation that changes an existing table.
The following code demonstrates how to execute on the :
Confirm the table was properly altered by using to execute a statement on the same table:
Code Example: TRUNCATE TABLE is a DDL (Data Definition Language) operation that deletes all data from an existing table.
The following code demonstrates how to execute on the :
The following query confirms that the statement deleted all rows from the :
This page is: Copyright © 2025 MariaDB. All rights reserved.
DESC contacts;+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| f_name | varchar(25) | YES | | NULL | |
| last_name | varchar(25) | YES | | NULL | |
| email | varchar(100) | YES | | NULL | |
+---------------+--------------+------+-----+---------+----------------+// Includes
#include <iostream>
#include <mariadb/conncpp.hpp>
// Function to Alter Table
void alterTable(std::shared_ptr<sql::Statement> &stmnt)
{
try {
// Alter contacts Table
stmnt->executeUpdate("ALTER TABLE test.contacts RENAME COLUMN first_name TO f_name");
}
// Catch Exception
catch (sql::SQLException& e) {
std::cerr << "Error altering table: "
<< e.what() << std::endl;
}
}
// Main Process
int main(int argc, char **argv)
{
try {
// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the other connection options
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(driver->connect(url, properties));
// Create a Statement
// Use a smart pointer for extra safety
std::shared_ptr<sql::Statement> stmnt(conn->createStatement());
// Use Statement to alter table
alterTable(stmnt);
// Close Connection
conn->close();
}
// Catch Exceptions
catch (sql::SQLException& e) {
std::cerr << "Error Connecting to the database: "
<< e.what() << std::endl;
// Exit (Failed)
return 1;
}
// Exit (Success)
return 0;
}// Includes
#include <iostream>
#include <mariadb/conncpp.hpp>
// Function to Truncate Table
void truncateTable(std::shared_ptr<sql::Statement> &stmnt)
{
try {
// TRUNCATE contacts Table
stmnt->executeUpdate("TRUNCATE test.contacts");
}
// Catch Exception
catch (sql::SQLException& e) {
std::cerr << "Error truncating table: "
<< e.what() << std::endl;
}
}
// Main Process
int main(int argc, char **argv)
{
try {
// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the other connection options
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(driver->connect(url, properties));
// Create a Statement
// Use a smart pointer for extra safety
std::shared_ptr<sql::Statement> stmnt(conn->createStatement());
// Use Prepared Statement to truncate table
truncateTable(stmnt);
// Close Connection
conn->close();
}
// Catch Exceptions
catch (sql::SQLException& e) {
std::cerr << "Error Connecting to the database: "
<< e.what() << std::endl;
// Exit (Failed)
return 1;
}
// Exit (Success)
return 0;
}SELECT * FROM test.contacts;Empty set (0.000 sec)C++ developers can use MariaDB Connector/C++ to perform basic DML (Data Manipulation Language) operations with MariaDB database products.
DML (Data Manipulation Language) refers to all SQL data statements in the SQL standard (ISO/IEC 9075-2:2016). Some examples of DML include , , , , and .
, , and are DML (Data Manipulation Language) operations that modify the data in a table.
The following code demonstrates how to execute an INSERT on the .
To update or delete data, replace the INSERT statement in the code example with an UPDATE or DELETE statement:
Confirm the data was properly inserted by using to execute a statement:
is a DML (Data Manipulation Language) operation that reads the data from a table.
The following code demonstrates how to execute SELECT on the :
Example output:
This page is: Copyright © 2025 MariaDB. All rights reserved.
Developers can use MariaDB Connector/C++ to perform basic DML (Data Manipulation Language) operations inside a transaction with MariaDB database products.
By default, MariaDB Connector/C++ enables auto-commit. When auto-commit is enabled, each SQL statement is executed in its own transaction.
Confirm the auto-commit is enabled by calling sql::Connection::getAutoCommit():
MariaDB Connector/C++ supports multi-statement transactions when the auto-commit is disabled.
Disable auto-commit by calling sql::Connection::setAutoCommit():
When auto-commit is disabled, a new transaction is automatically started when the current transaction is manually committed or rolled back. It means the application does not need to manually start each new transaction with or .
The transaction can be manually managed by performing the following operations:
Setting the transaction isolation by calling sql::Connection::setTransactionIsolation() or using .
Set the transaction to read-only by calling sql::Connection::setReadOnly() or using .
Create a savepoint by calling sql::Connection::setSavepoint() or using .
Roll back to a savepoint by calling sql::Connection::releaseSavepoint() or using .
Commit the transaction by calling sql::Connection::commit() or using .
Roll back the transaction by calling sql::Connection::rollback() or using .
, , and are DML (Data Manipulation Language) operations that modify data in a table.
The following code demonstrates how to execute on the example table within a transaction with auto-commit disabled.
To insert or delete data, replace the statement in the code example with an or statement:
The query below confirms the of the example table:
This page is: Copyright © 2025 MariaDB. All rights reserved.
SELECT * FROM test.contacts;bool isAutoCommit = conn->getAutoCommit();conn->setAutoCommit(false);// Includes
#include <iostream>
#include <mariadb/conncpp.hpp>
void updateContact(std::shared_ptr<sql::PreparedStatement> &stmnt,
sql::SQLString first_name,
sql::SQLString email)
{
try {
// Bind variables to prepared statement parameters
// Note that the index starts at 1--not 0
stmnt->setString(1, email);
stmnt->setString(2, first_name);
// Execute Statement
stmnt->executeUpdate();
}
// Catch Exception
catch (sql::SQLException &e) {
std::cerr << "Error updating contact: "
<< e.what() << std::endl;
}
}
// Main Process
int main(int argc, char **argv)
{
try {
// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the other connection options
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(driver->connect(url, properties));
// Use Connection to update contacts with a transaction
try {
// Disabling ``auto-commit`` mode automatically starts a new user managed transaction.
conn->setAutoCommit(false);
// Create a PreparedStatement
// Use a smart pointer for extra safety
std::shared_ptr<sql::PreparedStatement> stmnt(conn->prepareStatement(
"UPDATE test.contacts SET email=? WHERE first_name = ?"
)
);
std::string contacts[3][2] = {
{ "John", "johnsmith@example.com" },
{ "Jon", "jonsmith@example.com" },
{ "Johnny", "johnnysmith@example.com" }
};
for (int row { 0 }; row < 3; ++row) {
updateContact(stmnt, contacts[row][0], contacts[row][1]);
}
// Commit the transaction
conn->commit();
}
catch (sql::SQLException &e) {
std::cerr << "Error updating contact with a transaction: "
<< e.what() << std::endl;
// Rollback the transaction
conn->rollback();
}
// Close Connection
conn->close();
}
catch (sql::SQLException &e) {
std::cerr << "SQL exception in the database: "
<< e.what() << std::endl;
// Exit (Failed)
return 1;
}
// Exit (Success)
return 0;
}SELECT * FROM test.contacts;+----+------------+-----------+-------------------------+
| id | first_name | last_name | email |
+----+------------+-----------+-------------------------+
| 1 | John | Smith | johnsmith@example.com |
+----+------------+-----------+-------------------------+
| 2 | Jon | Smith | jonsmith@example.com |
+----+------------+-----------+-------------------------+
| 3 | Johnny | Smith | johnnysmith@example.com |
+----+------------+-----------+-------------------------+// Includes
#include <iostream>
#include <mariadb/conncpp.hpp>
// Function to Add Contact
void addContact(std::shared_ptr<sql::PreparedStatement> &stmnt,
sql::SQLString first_name,
sql::SQLString last_name,
sql::SQLString email)
{
try {
// Bind variables to prepared statement parameters
// Note that the index starts at 1--not 0
stmnt->setString(1, first_name);
stmnt->setString(2, last_name);
stmnt->setString(3, email);
// Execute Statement
stmnt->executeUpdate();
}
// Handle Exceptions
catch (sql::SQLException &e) {
std::cerr << "Error adding contact to database: "
<< e.what() << std::endl;
}
}
// Main Process
int main(int argc, char **argv)
{
try {
// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the other connection options
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(driver->connect(url, properties));
// Created a PreparedStatement
// Use a smart pointer for extra safety
std::shared_ptr<sql::PreparedStatement> stmnt(
conn->prepareStatement(
"INSERT INTO test.contacts(first_name, last_name, email) VALUES (?, ?, ?)"
)
);
// Use prepared statement to add data
addContact(stmnt, "John", "Smith", "john.smith@example.com");
// Close Connection
conn->close();
}
// Catch Exceptions
catch (sql::SQLException& e) {
std::cerr << "Error Connecting to the database: "
<< e.what() << std::endl;
// Exit (Failed)
return 1;
}
// Exit (Success)
return 0;
}+----+------------+-----------+------------------------+
| id | first_name | last_name | email |
+----+------------+-----------+------------------------+
| 1 | John | Smith | john.smith@example.com |
+----+------------+-----------+------------------------+// Includes
#include <iostream>
#include <mariadb/conncpp.hpp>
// Function to print Contacts
void printContacts(std::shared_ptr<sql::Statement> &stmnt)
{
try {
// Execute SELECT Statement
std::unique_ptr<sql::ResultSet> res(
stmnt->executeQuery("SELECT first_name, last_name, email FROM test.contacts")
);
// Loop over Result-set
while (res->next())
{
// Retrieve Values and Print Contacts
std::cout << "- "
<< res->getString("first_name")
<< " "
<< res->getString("last_name")
<< " <"
<< res->getString("email")
<< ">"
<< std::endl;
}
}
// Catch Exception
catch (sql::SQLException& e) {
std::cerr << "Error printing contacts: "
<< e.what() << std::endl;
}
}
// Main Process
int main(int argc, char **argv)
{
try {
// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the other connection options
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(driver->connect(url, properties));
// Create a Statement
// Use a smart pointer for extra safety
std::shared_ptr<sql::Statement> stmnt(conn->createStatement());
printContacts(stmnt);
// Close Connection
conn->close();
}
// Catch Exceptions
catch (sql::SQLException &e) {
std::cerr << "Error Connecting to the database: "
<< e.what() << std::endl;
// Exit (Failed)
return 1;
}
// Exit (Success)
return 0;
}- John Smith <john.smith@example.com>
- Jon Smith <jon.smith@example.com>
- Johnny Smith <johnny.smith@example.com>MariaDB Connector/C++ enables C++ applications to establish client connections to MariaDB database products over TLS.
MariaDB Connector/C++ supports two different formats for connection URLs, the JDBC syntax and the compatibility syntax.
MariaDB Connector/C++ supports a connection URL syntax similar to JDBC.
The JDBC syntax for connection URLs is:
The connection URL:
Requires jdbc:mariadb:// as the protocol component.
Requires the in the hostDescription field.
Accepts an optional database name. If no database is provided, the connection will not select a database.
Some example connection URLs using the JDBC syntax:
jdbc:mariadb:192.0.2.1/
jdbc:mariadb:192.0.2.1/?user=db_user&password=db_user_password
jdbc:mariadb:192.0.2.1/database?user=db_user&password=db_user_password
MariaDB Connector/C++ supports a connection URL syntax for compatibility with MySQL Connector/C++.
The compatibility syntax for connection URLs is only supported for the connection method.
The compatibility syntax for connection URLs is:
The connection URL:
Requires tcp: as the protocol component to connect via TCP/IP.
Requires unix: as the protocol component to connect via Unix socket file. The hostDescription field should be set to localhost, and the localSocket should be set in the properties when you call the connection method.
Requires pipe:// as the protocol component to connect via Windows named pipe. The
Some example connection URLs using the compatibility syntax:
tcp:192.0.2.1/
tcp:192.0.2.1:3307/
tcp:mariadb.example.com/
tcp:mariadb.example.com:3307/
The host description syntax for MariaDB Connector/C++ is:
The host description:
Requires the host field to set the destination host to connect.
Accepts the host field as a host name, IPv4 address, or IPv6 address to connect via TCP/IP.
Accepts the host field as localhost to connect via Unix socket file, when the localSocket
Some example host descriptions:
192.0.2.1
192.0.2.1:3307
mariadb.example.com
mariadb.example.com:3307
MariaDB Connector/C++ accepts optional connection parameters in multiple contexts for both :
They can be specified in a .
They can be specified in a Properties object.
MariaDB Connector/C++ supports several optional connection parameters:
Two categories of methods are available to establish a connection.
MariaDB Connector/C++ can connect using the non-static connect() methods in the sql::Driver class.
The non-static connect() methods in the sql::Driver class have the following prototypes:
Connection* connect(const SQLString& url, Properties& props);
Connection* connect(const SQLString& host, const SQLString& user, const SQLString& pwd);
Connection* connect(const Properties& props);
The non-static connect() methods in the sql::Driver class:
Require an instance of the sql::Driver class to establish a connection.
Accept both forms of .
Provide two prototypes that do not use connection URLs at all.
Return nullptr as the Connection* value when an error occurs, so applications should check the return value before use.
For example:
MariaDB Connector/C++ can connect using the static getConnection() methods in the sql::DriverManager class.
The static getConnection() methods in the sql::DriverManager class have the following prototypes:
static Connection* getConnection(const SQLString& url);
static Connection* getConnection(const SQLString& url, Properties& props);
static Connection* getConnection(const SQLString& url, const SQLString& user, const SQLString& pwd);
The static getConnection() methods in the sql::DriverManager class:
Do not require an instance of the sql::DriverManager class to establish a connection, because they are static.
Accept only the .
Throw an exception when an error occurs, so applications should use try { .. } catch ( .. ) { .. } to catch the exception.
For example:
The following code demonstrates how to connect using the :
The following code demonstrates how to connect with TLS (Transport Layer Security, the successor to SSL) for the :
This page is: Copyright © 2025 MariaDB. All rights reserved.
key=value format.jdbc:mariadb:192.0.2.1:3307/database?user=db_user&password=db_user_passwordjdbc:mariadb:mariadb.example.com/database?user=db_user&password=db_user_password
jdbc:mariadb:mariadb.example.com:3307/database?user=db_user&password=db_user_password
jdbc:mariadb:localhost/database?localSocket=/var/lib/mysql/mysql.sock&user=db_user&password=db_user_password
hostDescriptionlocalhostpipeRequires the host description in the hostDescription field.
unix:localhost/
pipe:localhost/
Accepts an optional portNumber field to set the TCP/IP port. If it is not provided, the TCP port 3306 is used by default.
Defines the connect timeout value in milliseconds. When set to 0, there is no connect timeout.
int
30000
enabledTlsCipherSuites
A list of permitted ciphers or cipher suites to use for TLS.
string
• enabledSslCipherSuites • enabledSSLCipherSuites
hostName
The host name, IPv4 address, or IPv6 address to connect via TCP/IP. This parameter is only supported by the connection method that does not use a connection URL. If a is provided, the host name, IPv4 address, or IPv6 address should be specified in the connection URL.
jdbcCompliantTruncation
This mode is enabled by default. This mode configures the connector to add STRICT_TRANS_TABLES to , which causes ES to handle truncation issues as errors instead of warnings.
bool
TRUE
keyPassword
Password for the private key.
string
• MARIADB_OPT_TLS_PASSPHRASE
localSocket
Defines the Unix socket file to use for connections to localhost via Unix domain socket. Specify the path of Unix socket file, which can be obtained by querying the system variable: SHOW GLOBAL VARIABLES LIKE'socket';
string
• socket ( connection method only)
log
Non-zero value turns on logging and determines logging level. 0 = no logging 1 = error 2 = warning 3 = info 4 = debug 5 = trace
int
0
logname
The name of file to write the log in. If logname set, and log is not, log will be set to 1(error). Default name is mariadbccpp.log, and it's written to %TEMP% or %USERPROFILE% or current dir on Windows, and in $HOME or in /tmp on other systems. Logging is synchronized between threads, but not between processes.
string
mariadbccpp.log
password
Defines the password of the user account to connect with.
pipe
Defines the name of the named pipe to use for connections to localhost via named pipe on Windows. Specify the name of the named pipe, which is MySQL by default.
string
prepStmtCacheSize
Defines the number of prepared statements that are cached for each connection. This parameter only applies if cachePrepStmts is enabled.
int
250
prepStmtCacheSqlLimit
Defines the maximum length for a prepared statement in the cache. This parameter only applies if cachePrepStmts is enabled. This value consists of length of query itself + length of schema name + 1
int
2048
rewriteBatchedStatements
An optimized mode of executeBatch/executeLargeBatch PreparedStatement methods execution. For INSERT queries, the connector will construct a single query using batch parameter sets. If used with useBulkStmts, rewriteBatchedStatements takes precedence.
schema
The database to select for the connection. If no database is provided, the connection will not select a database. This parameter is only supported by the connection method that does not use a connection URL. If a is provided, the database should be specified in the connection URL.
serverRsaPublicKeyFile
The name of the file that contains the RSA public key of the database server. The format of this file must be in PEM format. This option is used by the caching_sha2_password client authentication plugin.
string
• rsaKey
socketTimeout
Defines the network socket timeout (SO_TIMEOUT) in milliseconds. When set to 0, there is no socket timeout. This connection parameter is not intended to set a maximum time for statements. To set a maximum time for statements, please see the system variable.
int
0
• OPT_READ_TIMEOUT
tcpRcvBuf
The buffer size for TCP/IP and socket communication. tcpSndBuf changes the same buffer value, and the biggest value of the two is selected.
int
0x4000
• tcpSndBuf
tcpSndBuf
The buffer size for TCP/IP and socket communication. tcpRcvBuf changes the same buffer value, and the biggest value of the two is selected.
int
0x4000
• tcpRcvBuf
tlsCA
A path to a PEM file that should contain one or more X509 certificates for trusted Certificate Authorities (CAs).
string
• tlsCa • sslCA
tlsCAPath
A path to a directory that contains one or more PEM files that should each contain one X509 certificate for a trusted Certificate Authority (CA) to use. The directory specified by this option must be processed by the openssl rehash command. This option is only supported if the connector was built with OpenSSL.
string
• tlsCaPath • sslCAPath
tlsCert
Path to the X509 certificate file.
string
• sslCert
tlsCRL
Path to a PEM file that should contain one or more revoked X509 certificates.
string
• tlsCrl • sslCRL
tlsCRLPath
A path to a directory that contains one or more PEM files that should each contain one revoked X509 certificate. The directory specified by this option must be processed by the openssl rehash command. This option is only supported if the connector was built with OpenSSL.
string
• tlsCrlPath • sslCRLPath
tlsKey
File path to a private key file.
string
• sslKey
tlsPeerFP
A SHA1 fingerprint of a server certificate for validation during the TLS handshake.
string
• tlsPeerFp • MARIADB_OPT_SSL_FP
tlsPeerFPList
A file containing one or more SHA1 fingerprints of server certificates for validation during the TLS handshake.
string
• tlsPeerFpList • MARIADB_OPT_SSL_FP_LIST
trustServerCertificate
When using TLS, do not check server's certificate.
bool
TRUE
useBulkStmts
An optimized mode of executeBatch/executeLargeBatch PreparedStatement methods execution that uses the MariaDB bulk execution feature. If used with rewriteBatchedStatements, rewriteBatchedStatements takes precedence.
useCompression
Compresses network traffic between the client and server.
bool
FALSE
• CLIENT_COMPRESS
user
Defines the user name of the user account to connect with.
• userName ( connection method only)
useServerPrepStmts
Defines whether the connector uses server-side prepared statements using the , , and statements. By default, the connector uses client-side prepared statements.
bool
FALSE
useTls
Whether to force TLS. This enables TLS with the default system settings.
bool
FALSE
• useSsl • useSSL
autoReconnect
Defines whether the connector automatically reconnects after a connection failure.
bool
FALSE
• OPT_RECONNECT
cachePrepStmts
Defines whether the prepared statement cache is enabled.
bool
FALSE
connectTimeout
jdbc:mariadb://<hostDescription>/[<database>] [?<key1>=<value1>[&<key2>=<value2>]](tcp|unix|pipe)://<hostDescription>[/]<host>[:<portNumber>]jdbc:mariadb://192.0.2.1:3306/database?user=db_user&password=db_user_password// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the other connection options
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(driver->connect(url, properties));
if (!conn) {
cerr << "Invalid database connection" << endl;
exit (EXIT_FAILURE);
}try {
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the other connection options
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(DriverManager::getConnection(url, properties));
} catch (...) {
cerr << "Invalid database connection" << endl;
exit (EXIT_FAILURE);
}// Includes
#include <iostream>
#include <mariadb/conncpp.hpp>
// Main Process
int main(int argc, char **argv)
{
try {
// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the other connection options
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(driver->connect(url, properties));
// Use Connection
// ...
// Close Connection
conn->close();
}
// Catch Exceptions
catch (sql::SQLException& e) {
std::cerr << "Error Connecting to the database: "
<< e.what() << std::endl;
// Exit (Failed)
return 1;
}
// Exit (Success)
return 0;
}// Includes
#include <iostream>
#include <mariadb/conncpp.hpp>
// Main Process
int main(int argc, char **argv)
{
try {
// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
// The URL or TCP connection string format is
// ``jdbc:mariadb://host:port/database``.
sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/test");
// Use a properties map for the user name and password
//The ``useTls`` option enables TLS
//The ``tlsCA`` option specifies path to a PEM file that contains a X509 certificate for trusted Certificate Authorities (CAs).
sql::Properties properties({
{"user", "db_user"},
{"password", "db_user_password"},
{"useTls", "true"},
{"tlsCA", "tls-ca-root.pem"}
});
// Establish Connection
// Use a smart pointer for extra safety
std::unique_ptr<sql::Connection> conn(driver->connect(url, properties));
// Use Connection
// ...
// Close Connection
conn->close();
}
// Catch Exceptions
catch (sql::SQLException& e) {
std::cerr << "Error Connecting to the database: "
<< e.what() << std::endl;
// Exit (Failed)
return 1;
}
// Exit (Success)
return 0;
}This page is: Copyright © 2025 MariaDB. All rights reserved.