MariaDB Connector/C++

MariaDB Connector/C++ enables C++ applications to connect to MariaDB Platform.

Overview

Connector

MariaDB Connector/C++

Supported Versions

1.0

Programming Language

C++11

License

GNU Lesser General Public License v2.1

Benefits of Connector/C++

C++ applications can connect to MariaDB Platform 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++

Connector/C

Executes SQL

Yes

Yes

Object-Oriented

Yes

No

Smart Pointers

Yes

No

Implements JDBC API

Yes

No

Setup for Examples

Examples in this MariaDB Connector/C++ documentation depend on a database test and table contacts.

Set up the example database and table:

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 a user db_user with privileges to execute the examples:

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;

Note

Please choose a password that meets your organization's password policies. If your MariaDB Enterprise Server instance has a password validation plugin installed, then the password must also meet the configured requirements.

By default, MariaDB Enterprise Server installs the simple_password_check plugin, configured with system variables:

Installation

MariaDB Connector/C++ is available for download as a binary tarball for Linux distributions and as an MSI for Microsoft Windows operating systems. It is dependent on MariaDB Connector C 3.1.1 or later.

Installing MariaDB Connector/C++ via Binary Tarball (Linux)

To install MariaDB Connector/C++ on Linux:

  1. Install the MariaDB Connector/C dependency.

  2. Go to the MariaDB Connector C++ download page.

  3. In the "OS" drop-down, select the Linux distribution you want to use.

  4. Click the "Download" button to download the binary tarball.

  5. Extract the tarball:

    $ tar -xvzf mariadb-connector-cpp-*.tar.gz
    
  6. Change into the relevant directory:

    $ cd mariadb-connector-cpp-*/
    
  7. Install the include directories:

    $ sudo install -d /usr/include/mariadb/conncpp
    $ sudo install -d /usr/include/mariadb/conncpp/compat
    
  8. Install the include files:

    $ 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
    
  9. Install the library directories:

    • On RHEL/CentOS:

      $ sudo install -d /usr/lib64/mariadb
      $ sudo install -d /usr/lib64/mariadb/plugin
      
    • On Debian/Ubuntu:

      $ sudo install -d /usr/lib/mariadb
      $ sudo install -d /usr/lib/mariadb/plugin
      
  10. Install the library files:

    • On RHEL/CentOS:

      $ sudo install lib/mariadb/libmariadbcpp.so /usr/lib64
      $ sudo install lib/mariadb/plugin/* /usr/lib64/mariadb/plugin
      
    • On Debian/Ubuntu:

      $ sudo install lib/mariadb/libmariadbcpp.so /usr/lib
      $ sudo install lib/mariadb/plugin/* /usr/lib/mariadb/plugin
      

Installing MariaDB Connector/C++ via MSI (Windows)

To install MariaDB Connector/C++ on Windows:

  1. MariaDB Connector/C dependency will be installed when Connector/C++ is installed.

  2. Go to the MariaDB Connector C++ download page for MS Windows.

  3. Click the "Download" button to download the MSI package.

  4. Run the MSI package and click "Next" to start the Setup Wizard.

  5. On the second screen, click the license agreement checkbox, then click "Next."

  6. On the third screen, click "Typical."

  7. On the fourth screen, click "Install."

  8. Click "Finish."

  9. Add the directory path that contains the mariadbcpp LIB file (example "C:\Program Files\MariaDB\MariaDB C++ Connector 64-bit") to PATH environment variable.

Developing with the Connector

To develop a C++ application with MariaDB Connector/C++ you will need to know:

Building the C++ Application

When you build your C++ application, your compiler needs to link your application with the MariaDB Connector/C++ shared library.

The following g++ (GNU GCC) command demonstrates how to link an application with the shared library using the -lmariadbcpp argument:

$ g++ -o example example.cpp -std=c++11 -lmariadbcpp

If you are not using the g++ compiler, please consult your compiler's manual.

Header Files

C++ applications developed using MariaDB Connector/C++ must include the connector's header files:

  • The C++ application must include the conncpp.hpp header file to use MariaDB Connector/C++.

  • Including conncpp.hpp in the application will automatically include other header files that are included by conncpp.hpp. You may need to inspect these header files to view the definitions of classes, functions, and methods:

    • CallableStatement.hpp

    • Connection.hpp

    • DatabaseMetaData.hpp

    • Driver.hpp

    • DriverManager.hpp

    • Exception.hpp

    • jdbccompat.hpp

    • ParameterMetaData.hpp

    • PreparedStatement.hpp

    • ResultSet.hpp

    • ResultSetMetaData.hpp

    • Savepoint.hpp

    • SQLString.hpp

    • Statement.hpp

    • Types.hpp

    • Warning.hpp

All header files are installed in the mariadb/conncpp/ directory. All classes, functions, and methods within those header files are declared in the sql namespace.

Classes

C++ applications developed using MariaDB Connector/C++ will use multiple classes:

Class

Description

sql::Connection

Establish a connection to MariaDB Platform. A Connection can be closed by calling close(), or there is an implicit close when using a smart pointer.

sql::PreparedStatement

Execute a query that contains variable text. Use of prepared statements reduces risk of SQL injection attacks. A PreparedStatement can be closed by calling close(), or there is an implicit close when using a smart pointer.

sql::ResultSet

Fetch query results. A ResultSet can be closed by calling close(), or there is an implicit close when using a smart pointer.

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::DatabaseMetaData

Provides detailed information about the database metadata, such as database name, version, schemas, tables, columns, procedures, and support for various features.

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.

Connections

MariaDB Connector/C++ enables C++ applications to establish client connections over TLS.

MariaDB Connector/C++ supports connections to:

Connection URL Syntax

The connection url syntax used to connect to MariaDB with Connector/C++ is as follows in which optional parameters are shown enclosed in []:

jdbc:mariadb://<hostDescription>/[database>] [?<key1>=<value1>[&<key2>=<value2>]] }

The hostDescription in the connection URL has a simple syntax and a complex syntax. The simple syntax is as follows:

<host>:<portnumber>

An example of connection url using the simple syntax for hostDescription is jdbc:mariadb://192.0.2.1:3306/database?user=db_user&password=db_user_password.

The preceding example for connection url includes two of the default options; user and password for the user name and user password respectively. MariaDB Connector/C++ supports several other default options, all of which are optional. Options related to connecting to MariaDB are:

Option Name

Description

Type

Default

Aliases

autoReconnect

Enable or disable automatic reconnect.

bool

false

  • OPT_RECONNECT

connectTimeout

The connect timeout value, in milliseconds, or zero for no timeout.

int

30000

enabledTlsCipherSuites

A list of permitted ciphers or cipher suites to use for TLS.

string

  • enabledSslCipherSuites

  • enabledSSLCipherSuites

jdbcCompliantTruncation

This mode is enabled by default. This mode configures the connector to add STRICT_TRANS_TABLES to sql_mode, 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

For connections to localhost, the Unix socket file to use.

string

pipe

On Windows, specify the named pipe name to connect.

string

serverRsaPublicKeyFile

The name of the file which 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

Specifies the timeout in seconds for reading packets from the server. Value of 0 disables this timeout.

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.

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 needs to 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

useCompression

Compresses network traffic between the client and server.

bool

false

  • CLIENT_COMPRESS

useServerPrepStmts

Whether to use Server Side Prepared Statements(SSPS) for PreparedStatement by default, and not client side ones(CSPS).

bool

false

useTls

Whether to force TLS. This enables TLS with the default system settings.

bool

  • useSsl

  • useSSL

Connection Methods

Two categories of methods are available to to establish a connection.

The first category of methods are the non-static connect() methods in the sql::Driver class, which 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 connect() methods in the sql::Driver class:

  • Require an instance of the sql::Driver class to establish a connection

  • Return nullptr as the Connection* value when an error occurs, so applications should check the return value before use

For example:

// 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
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));

The second category of methods are the static getConnection() methods in the sql::DriverManager class, which 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 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

  • Throw an exception when an error occurs, so applications should use try { .. } catch ( .. ) { .. } to catch the exception.

For example:

// 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
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));

Establishing Connections

The following code demonstrates how to connect using the example database and user account:

// 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
      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 MariaDB Platform: "
         << e.what() << std::endl;

      // Exit (Failed)
      return 1;
   }

   // Exit (Success)
   return 0;
}

Connecting with TLS

The following code demonstrates how to connect with TLS (Transport Layer Security, the successor to SSL) for the example database and user account:

// 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 MariaDB Platform: "
         << e.what() << std::endl;

      // Exit (Failed)
      return 1;
   }

   // Exit (Success)
   return 0;
}

Inserting, Updating, or Deleting Data

INSERT, UPDATE, and DELETE are DML (Data Manipulation Language) operations. The following code demonstrates how to execute INSERT on the example table. To update or delete data, replace the INSERT statement in the example code with an UPDATE or DELETE statement:

// 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 user name and password
      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 MariaDB Platform: "
         << e.what() << std::endl;

      // Exit (Failed)
      return 1;
   }

   // Exit (Success)
   return 0;
}

The following query confirms the INSERT into the example table:

SELECT * from test.contacts;
+----+------------+-----------+------------------------+
| id | first_name | last_name | email                  |
+----+------------+-----------+------------------------+
|  1 | John       | Smith     | john.smith@example.com |
+----+------------+-----------+------------------------+

Selecting Data

The following code demonstrates how to execute SELECT on the example table:

// 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 user name and password
      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 MariaDB Platform: "
         << e.what() << std::endl;

      // Exit (Failed)
      return 1;
   }

   // Exit (Success)
   return 0;
}

Example output:

- John Smith <john.smith@example.com>
- Jon Smith <jon.smith@example.com>
- Johnny Smith <johnny.smith@example.com>

Transactions

By default, MariaDB Connector/C++ enables auto-commit. When auto-commit is enabled, each SQL statement is executed in its own transaction. Your application can manually manage transactions by disabling auto-commit.

When auto-commit is disabled, a new transaction is automatically started when the current transaction is manually committed or rolled back. This means your application does not need to manually start each new transaction with BEGIN or START TRANSACTION.

Updating Data within a Transaction

UPDATE, INSERT, and DELETE are DML (Data Manipulation Language) operations. The following code demonstrates how to execute UPDATE on the example table within a user-managed transaction. To insert or delete data, replace the UPDATE statement in the example code with an INSERT or DELETE statement:

// 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 user name and password
      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 MariaDB Platform: "
         << e.what() << std::endl;

      // Exit (Failed)
      return 1;
   }

   // Exit (Success)
   return 0;
}

The following query confirms the UPDATE of the example table:

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 |
+----+------------+-----------+-------------------------+

Altering a Table

ALTER TABLE is a DDL (Data Definition Language) operation. The following code demonstrates how to execute ALTER TABLE on the example table:

// 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 user name and password
      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 MariaDB Platform: "
         << e.what() << std::endl;

      // Exit (Failed)
      return 1;
   }

   // Exit (Success)
   return 0;
}

Truncating a Table

TRUNCATE TABLE is a DDL (Data Definition Language) operation. The following code demonstrates how to execute TRUNCATE on the example table:

// 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 user name and password
      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 MariaDB Platform: "
         << e.what() << std::endl;

      // Exit (Failed)
      return 1;
   }

   // Exit (Success)
   return 0;
}

The following query confirms that the TRUNCATE statement deleted all rows from the example table:

SELECT * from test.contacts;
Empty set (0.000 sec)

Sample Application

tasks.cpp is a complete sample application that demonstrates CRUD (Create, Read, Update, Delete) operations using the MariaDB Connector/C++.

tasks.cpp Sample Application Setup

The tasks.cpp sample application depends on a database todo and table tasks.

Set up the example database and table:

CREATE DATABASE IF NOT EXISTS todo;

CREATE TABLE todo.tasks (
   id int AUTO_INCREMENT PRIMARY KEY,
   description varchar(200),
   completed boolean DEFAULT false);

Create a user db_user with privileges to execute the tasks sample application:

CREATE 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;

Within the tasks.cpp file, navigate to the main method, and add your database connection values:

sql::SQLString url("jdbc:mariadb://192.0.2.1:3306/todo");
sql::Properties properties({{"user", "db_user"}, {"password", "db_user_password"}});

Building tasks.cpp

The following command builds the sample application:

g++ -o tasks tasks.cpp -std=c++11 -lmariadbcpp

tasks.cpp Usage

Create a new task record:

./tasks addTask 'New Task Description'

Read all task records:

./tasks showTasks

If the task got added, the preceding command lists the task:

id = 1, description = New Task Description, completed = 0

Update an existing task record:

./tasks updateTaskStatus 1 1

If the task got updated, the ./tasks showTasks command lists the updated task:

id = 1, description = New Task Description, completed = 1

Delete a task record:

./tasks deleteTask 1