Only this pageAll pages
Powered by GitBook
Couldn't generate the PDF for 289 pages, generation stopped at 100.
Extend with 50 more pages.
1 of 100

Connectors

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

MariaDB Connectors

Complete MariaDB Connectors guide. Complete reference for client libraries in Python, Java, Node.js, C, C++, ODBC, and R languages for production use.

Quickstart GuidesConnector/CConnector/C++Connector/JConnector/R2DBC.NET ConnectorConnector/Node.jsConnector/ODBCConnector/PythonOther Connectors & Methods

Quickstart Guides

Dive into MariaDB Connectors with quickstart guides. Learn how to swiftly set up and use official client libraries (C, Java, Python, Node.js, ODBC) for seamless application connectivity.

Connector/C

The MariaDB Connector/C is used to connect applications developed in C/C++ to MariaDB and MySQL databases. MariaDB Connector/C is LGPLv2.1 licensed.

MariaDB Connector/C is the C client library for connecting C/C++ applications to MariaDB and MySQL databases. It is LGPLv2.1 licensed.

MariaDB Connector/C Overview

Complete Connector/C reference: Windows MSI install, Linux packages (yum/apt/zypper), MariaDB-shared/devel libraries, and option file configuration.

Install MariaDB Connector/C

Install MariaDB Connector/C on Linux, Windows, and macOS, with configuration and verification steps for production use.

Configuring MariaDB Connector/C with Option Files

MariaDB Connector/C reads connection settings from option files such as my.cnf, supporting default and custom file locations, option groups, and a full set of client options.

MariaDB Binlog/Replication API reference

MariaDB Connector/C binlog and replication API reference, documenting the functions used to consume binary log events from a MariaDB server as a replication client.

MariaDB Connector/C Data Structures

Reference for the public data structures in MariaDB Connector/C, including MYSQL, MYSQL_RES, MYSQL_STMT, MYSQL_FIELD, MYSQL_BIND, and MYSQL_TIME with all member definitions.

MariaDB Connector/C Plugins

MariaDB Connector/C supports loadable and built-in plugins across four categories: connection, pvio, I/O, and authentication, including remote_io and multiple auth methods.

MariaDB Connector/C Types and Definitions

Reference for MariaDB Connector/C types and definitions, including enumeration constants for field types, statement options, cursor types, indicator types, field flags, and server status.

Building Connector/C From Source

Build MariaDB Connector/C from source: download the package from MariaDB downloads or get the latest development version from the Connector/C GitHub repository.

MariaDB Connector/C API Functions

Detailed documentation on the MariaDB Connector/C API functions for connecting, querying, and managing data in C applications.

mariadb_rpl_extract_rows()

Extracts row data from a replication event and returns a linked list of individual row change records for further processing.

Syntax

Parameters

Parameter
Description

rpl

A replication handle previously allocated by mariadb_rpl_init().

tm_event

The last TABLE_MAP_EVENT, which defines the table structure and column metadata.

row_event

The row event (WRITE_ROWS_EVENT, UPDATE_ROWS_EVENT, or DELETE_ROWS_EVENT) containing the raw row data to decode.

Return Value

Returns a pointer to a linked list of MARIADB_RPL_ROW structures on success, or NULL on failure. Each node in the list represents one row in the event.

History

Added in MariaDB Connector/C 3.3.5.

See also

  • mariadb_rpl_fetch()

mariadb_rpl_errno()

Returns the error number for the most recent Binlog API function call that can succeed or fail.

Syntax

Parameters

Parameter
Description

rpl

A replication handle, previously allocated by mariadb_rpl_init().

Return Value

Returns the error number on failure, or 0 if no error has occurred.

Notes

Client error codes are defined in errmsg.h. Server error codes are defined in mysqld_error.h in the MariaDB server source distribution.

Use mariadb_rpl_errno() to distinguish between a true error and a normal end-of-stream condition when mariadb_rpl_fetch() returns NULL.

History

Added in MariaDB Connector/C 3.3.5.

See also

  • mariadb_rpl_error()

mariadb_rpl_error()

Returns the error message for the most recent Binlog API function call that can succeed or fail.

Syntax

Parameters

Parameter
Description

rpl

A replication handle previously allocated by mariadb_rpl_init().

Returns

Returns a null-terminated string containing the error message on failure, or an empty string ("") if no error has occurred.

Notes

Client error codes are defined in errmsg.h. Server error codes are defined in mysqld_error.h in the MariaDB server source distribution.

History

Added in MariaDB Connector/C 3.3.5.

See also

mariadb_rpl_errno()

Example

The following example illustrates the complete workflow of the Binlog API. It configures the connection by setting the required session variables, initializes and prepares the replication handle, retrieves all available events, processes each event type appropriately, and performs proper cleanup at the end.


#include <mysql.h>
#include <mariadb_rpl.h>

static int read_events(MYSQL *mysql)
{
  MARIADB_RPL_EVENT *event= NULL;
  MARIADB_RPL *rpl= mariadb_rpl_init(mysql);

  mysql_query(mysql, "SET @mariadb_slave_capability=4");
  mysql_query(mysql, "SET @slave_gtid_strict_mode=1");
  mysql_query(mysql, "SET @slave_gtid_ignore_duplicates=1");
  mysql_query(mysql, "SET NAMES utf8");
  mysql_query(mysql, "SET @master_binlog_checksum= @@global.binlog_checksum");

  mariadb_rpl_optionsv(rpl, MARIADB_RPL_SERVER_ID, 12);
  mariadb_rpl_optionsv(rpl, MARIADB_RPL_START, 4);
  mariadb_rpl_optionsv(rpl, MARIADB_RPL_FLAGS, MARIADB_RPL_BINLOG_SEND_ANNOTATE_ROWS)

  if (mariadb_rpl_open(rpl))
    return FAIL;

  while((event= mariadb_rpl_fetch(rpl, event)))
  {
    /* process events */
    switch(event->event_type) {
      case BINLOG_CHECKPOINT_EVENT:
        ....
        break;
      case FORMAT_DESCRIPTION_EVENT:
        ...
        break;
      ....
      default:
        printf("Unknown event: %d", event->event_type);
        break;
    }
  }
  mariadb_free_rpl_event(event);
  mariadb_rpl_close(rpl);
  return OK;
}

Building Connector/C From Source

Build MariaDB Connector/C from source. Download the package from MariaDB downloads or get the latest development version from the Connector/C GitHub repository.

Prerequisites For Building Connector/C From Source

Building MariaDB Connector/C from source requires CMake, a C compiler, and TLS/SSL libraries. Windows needs Visual Studio; Linux and macOS need gcc, with optional Curl or Kerberos.

Configuration Settings for Building Connector/C

Configure the MariaDB Connector/C build via CMake options including build type, TLS/SSL backend, install prefix, and client plugins such as authentication and connection handlers.

Compiling Connector/C

Compile MariaDB Connector/C after configuration using CMake on Windows or Unix. Supports Visual Studio builds and GNU make, with both IDE and command-line build options.

mariadb_connect

Connect to a database server using a connection string

Syntax

Parameter

  • mysql - mysql handle, which was previously allocated by mysql_init() and connected by mysql_real_connect().

  • conn_str- Connection string, containing connection parameters. A connection string contains key/value pairs, separated by a semicolon as used in ODBC. Supported keys are all configuration options which can be used in MariaDB configuration files. For a complete list check the chapter configuration files.

Return Value

Returns a MYSQL * handle or NULL on error.

Note

  • The connection string must contain at least one semicolon, otherwise it will be interpreted as hostname.

  • Unknown or invalid keys will be ignored

  • mariadb_connect is not a function, but a macro which maps to mysql_real_connect: #define mariadb_connect(mysql, conn_str) mysql_real_connect((mysql),(conn_str), NULL, NULL, NULL, 0, NULL, 0)

Example

History

mariadb_connect() was added in Connector/C 3.3.0.

mariadb_connection

Syntax

Parameter

mysql - mysql handle, which was previously allocated by mysql_init() and connected by mysql_real_connect().

Description

Checks if the client is connected to a MariaDB or MySQL database server.

Return Value

Returns a non zero value if connected to a MariaDB database server, otherwise zero.

mariadb_convert_string

Syntax

#include <mysql.h>

size_t mariadb_convert_string(const char *from __attribute__((unused)),
                              size_t *from_len __attribute__((unused)),
                              MARIADB_CHARSET_INFO *from_cs __attribute__((unused)),
                              char *to __attribute__((unused)),
                              size_t *to_len __attribute__((unused)),
                              MARIADB_CHARSET_INFO *to_cs __attribute__((unused)), int *errorcode)

Description

Converts a string in to a different character set

This function is deprecated.

mariadb_get_info

Syntax

Description

Retrieves generic or connection related information.

This function is deprecated. Please use mariadb_get_infov() instead.

See Also

  • mariadb_get_infov()

mysql_client_find_plugin

Syntax

Parameters

  • mysql is a connection identifier, which was previously initialized by mysql_init() and optional connected by mysql_real_connect().

  • name The name of the plugin.

  • type The plugin type.

Valid Plugin Types

  • MYSQL_CLIENT_AUTHENTICATION_PLUGIN

  • MARIADB_CLIENT_PVIO_PLUGIN

  • MARIADB_CLIENT_REMOTEIO_PLUGIN

  • MARIADB_CLIENT_CONNECTION_PLUGIN or MARIADB_CLIENT_COMPRESSION_PLUGIN.

Return Value

A pointer to the plugin handle, or NULL if an error occurred.

If the type of the plugin is not known, -1 needs to be specified for parameter type.

See Also

  • mysql_load_plugin()

mysql_eof

Syntax

Parameter

Parameter
Description

result

A result set handle returned by mysql_store_result().

Description

mysql_eof determines whether the final row in a result set has already been retrieved.

Return Value

Returns non-zero (true) if the entire result set has been read, or zero (false) if rows are still available.

Deprecated. mysql_eof is deprecated. To determine the end of a result set, check the return value of mysql_fetch_row instead: a NULL return indicates that all rows have been fetched.

When the result set was acquired via mysql_store_result(), mysql_eof always returns true because the entire result is buffered in memory at retrieval time.

See Also

  • mysql_fetch_row()

  • mysql_store_result()

mysql_net_field_length

Syntax

Parameter

Parameter
Description

packet

A pointer to a pointer to the current position in the packet buffer.

Description

Returns the length of a length encoded field and increments the pointer to the beginning of the field.

Return Value

Returns the length of the field.

This function is part of the low level protocol API and can be used to retrieve data if a callback function was provided for fetching results from prepared statements.

See Also

  • mysql_net_read_packet()

mysql_net_read_packet

Syntax

Parameter

Parameter
Description

mysql

A connection handle previously allocated by mysql_init() and connected by mysql_real_connect().

Description

mysql_net_read_packet reads the next protocol packet from the server into the connection's internal network buffer.

Return Value

Returns the length of the received packet.

This function is part of the low level protocol API.

See also

  • mysql_net_field_length()

#include <mariadb_rpl.h>

MARIADB_RPL_ROW *mariadb_rpl_extract_rows(
    MARIADB_RPL *rpl,
    MARIADB_RPL_EVENT *tm_event,
    MARIADB_RPL_EVENT *row_event);
#include <mariadb_rpl.h>

uint32_t mariadb_rpl_errno(MARIADB_RPL *rpl);
#include <mariadb_rpl.h>

const char *mariadb_rpl_error(MARIADB_RPL *rpl);
#include <mysql.h>

MYSQL *mariadb_connect(MYSQL * mysql, const char *conn_str);
if (!mariadb_connect(mysql, "host=localhost;database=test;ssl_enforce=1"))
{
  printf("Error: %s\n", mysql_error(mysql));
  return 1;
}
#include <mysql.h>

my_bool mariadb_connection(MYSQL * mysql);
#include <mysql.h>

my_bool mariadb_get_info(MYSQL *mysql, enum mariadb_value value, void *arg)
#include <mysql.h>
struct st_mysql_client_plugin * 
mysql_client_find_plugin(MYSQL *mysql, const char *name, int type);
#include <mysql.h>

my_bool mysql_eof(MYSQL_RES *result);
#include <mysql.h>

unsigned long mysql_net_field_length(unsigned char **packet)
#include <mysql.h>

unsigned long mysql_net_read_packet(MYSQL *mysql)

MariaDB Connector/C++ Guide

Quickstart Guide for Connector/C++

MariaDB Connector/C++ Quickstart Guide

MariaDB Connector/C++ allows your C++ applications to connect to MariaDB databases, including support for TLS encryption. It provides an object-oriented design and leverages smart pointers for efficient memory management.

The most recent Stable (GA) release is MariaDB Connector/C++ 1.1.6.

Why Choose Connector/C++?

While you can use MariaDB Connector/C for C++ applications, Connector/C++ offers specific advantages for C++ development:

Feature

Connector/C++

Connector/C

Executes SQL

Yes

Yes

Object-Oriented

Yes

No

Smart Pointers

Yes

No

Implements JDBC API

Yes

No

Next Steps

To get started with MariaDB Connector/C++, you'll typically need to:

  1. Download the Connector/C++ library. Look for the appropriate package for your operating system and development environment.

  2. Integrate the library into your C++ project. This usually involves including header files and linking against the library during compilation.

  3. Write C++ code to establish a connection, execute SQL queries, and process results using the object-oriented API.

This page is: Copyright © 2025 MariaDB. All rights reserved.

Erlang Guide

Quickstart Guide for MySQL/OTP (Erlang/OTP Client)


MySQL/OTP is the native Erlang/OTP client for connecting Erlang applications to MariaDB and MySQL databases, offering a direct implementation of the MySQL protocol.

1. Installation

Add MySQL/OTP as a dependency in your rebar.config file (for rebar3 projects):

Erlang

{deps, [
    {mysql, ".*", {git, "https://github.com/mysql-otp/mysql-otp.git", {tag, "2.0.0"}}} % Use the latest stable tag
]}.

Then, run rebar3 compile.

2. Basic Usage

Here are essential steps for connecting and interacting with your database:

a. Connect:

Erlang

{ok, Pid} = mysql:start_link([{host, "localhost"}, {user, "myuser"}, {password, "mypass"}, {database, "mydb"}]).

Replace placeholder values with your actual database credentials.

b. Execute Query:

Erlang

% Select data
{ok, ColumnNames, Rows} = mysql:query(Pid, <<"SELECT id, name FROM mytable WHERE status = ?">>, [<<"active">>]).

% Insert data
ok = mysql:query(Pid, "INSERT INTO mytable (col1, col2) VALUES (?, ?)", [<<"value1">>, 123]).

c. Close Connection:

Erlang

mysql:stop(Pid).

Further Resources:

  • MySQL/OTP GitHub Repository

  • Erlang/OTP Documentation

MariaDB Binlog/Replication API reference

MariaDB Connector/C binlog and replication API reference, documenting the functions used to consume binary log events from a MariaDB server as a replication client.

The Binlog/Replication API enables client applications to connect to a MariaDB server and stream its binary log as replication events. When binary logging is enabled, the log records all data manipulation and definition changes.

This API is particularly useful for building change‑data capture (CDC) pipelines, custom replication consumers, and auditing tools.

Binlog/API Data Structures

All structures and type definitions for the Binlog/Replication API, defined in include/mariadb_rpl.h.

Replication API Types and Definitions

All enumerations and preprocessor definitions for the Binlog/Replication API, defined in include/mariadb_rpl.h.

Replication API Function Reference

All functions in the Binlog/Replication API, defined in include/mariadb_rpl.h.

Replication API Function Reference

All functions in the Binlog/Replication API are defined in include/mariadb_rpl.h

The Binlog/Replication API provides a low‑level interface for consuming and processing binary log events from a MariaDB server. It allows applications to configure replication handles, open streams, fetch and decode events, and manage errors.

Together, these functions enable developers to build custom replication clients and event processing tools.

Function Overview

Function
Description

mariadb_rpl_init()

Allocates and initializes a replication handle associated with an existing database connection.

Syntax

#include <mysql.h>
#include <mariadb.h>

MARIADB_RPL *mariadb_rpl_init(MYSQL *mysql)

Parameters

Parameter
Description

mysql

A connection handle previously connected via mysql_real_connect()

Return Value

A pointer to a newly allocated MARIADB_RPL handle on success, or NULL on failure.

Notes

The replication handle must be released by calling mariadb_rpl_close() when no longer needed.

History

Added in .

See also

  • mariadb_rpl_close()

mariadb_rpl_optionsv()

Sets options on a replication handle. All required options must be set before calling .

Parameter
Description

mariadb_rpl_get_optionsv()

Retrieves the current value of a replication handle option previously set with mariadb_rpl_optionsv().

Syntax

#include <mariadb_rpl.h>

int mariadb_rpl_get_optionsv(MARIADB_RPL *rpl,
                               enum mariadb_rpl_option option,
                               ...);

Parameters

Parameter
Description

rpl

A replication handle previously allocated by .

option

Option
Output type
Description

Returns zero on success, non-zero if the option is not recognized.

Added in .

mariadb_rpl_open()

Opens a binary log stream. Registers the client as a replica with the connected server and begins streaming binary log events.

Syntax

#include <mariadb_rpl.h>

int mariadb_rpl_open(MARIADB_RPL *rpl);

Parameters

Parameter
Description

rpl

A replication handle, previously allocated by mariadb_rpl_init(). At a minimum, MARIADB_RPL_SERVER_ID must have been set before this call.

Return Value

Returns zero on success, non-zero on failure. Call mariadb_rpl_error() to retrieve the error message.

History

Added in .

See Also

  • mariadb_rpl_init()

mariadb_rpl_fetch()

Fetches the next event from an open binary log stream.

Syntax

#include <mariadb_rpl.h>

MARIADB_RPL_EVENT *mariadb_rpl_fetch(MARIADB_RPL *rpl,
                                      MARIADB_RPL_EVENT *event);

Parameters

Parameter
Description

rpl

An open replication handle initialized by mariadb_rpl_init() and connected by mariadb_rpl_open().

event

An event returned by a previous call to mariadb_rpl_fetch. If this parameter is set to NULL, the function allocates new memory for the event. If a non‑NULL value is provided, the existing event structure is overwritten with the new data.

Return Value

Returns a pointer to a MARIADB_RPL_EVENT structure containing the next event on success, or NULL when the EOF packet is received or an error occurs.

Note

Event memory must be freed by calling mariadb_free_rpl_event() when the event is no longer needed.

History

Added in .

See also

  • mariadb_free_rpl_event()

  • mariadb_rpl_extract_rows()

mariadb_free_rpl_event()

Frees the memory allocated for a MARIADB_RPL_EVENT structure returned by mariadb_rpl_fetch().

Syntax

#include <mariadb_rpl.h>

void mariadb_free_rpl_event(MARIADB_RPL_EVENT *event);

Parameters

Parameter
Description

event

A pointer previously returned by mariadb_rpl_fetch(). Passing NULL is safe and has no effect.

Return Value

None

Notes

Avoid calling this function on an event pointer that will be passed back to mariadb_rpl_fetch() for reuse. Only call it when you are done processing the event and will not reuse the pointer.

History

Added in .

See Also

  • mariadb_rpl_fetch()

mariadb_rpl_close()

Closes a binary log stream and releases all resources associated with the replication handle.

Syntax

#include <mariadb_rpl.h>

void mariadb_rpl_close(MARIADB_RPL *rpl);

Parameters

Parameter
Description

rpl

A replication handle previously allocated by mariadb_rpl_init() and and connected using mariadb_rpl_open()

Notes

This function closes the replication stream and frees the MARIADB_RPL handle, but does not close the underlying database connection. To close the connection, call mysql_close() separately after mariadb_rpl_close().

History

Added in .

See Also

  • mariadb_rpl_init()

  • mariadb_rpl_open()

MariaDB Connector/C Plugins

MariaDB Connector/C supports loadable and built-in plugins across four categories: connection, pvio, I/O, and authentication, including remote_io and multiple auth methods.

MariaDB Connector/C functionality can be extended via loadable (or statically compiled in) plugins. As of the version 3.1.11 Connector/C comes with the following plugins

connection plugins

replication

pvio plugins

These plugins are used by the Connector/C to communicate with the MariaDB server.

socket

npipe

shmem

io plugins

These are plugins that are used whenever Connector/C needs to read a file. For example, for LOAD DATA LOCAL INFILE statement, when a server requests the Connector/C to send a specific file.

remote_io

This plugin uses libcurl to access remote files, it allows the client to execute statements like

LOAD DATA LOCAL INFILE 'http://mariadb.com/example.csv' INTO t1

Note that here, like with any LOAD DATA LOCAL, it'll be the client that fetches the file, not the server.

This plugin supports the following url schemes: http://, https://, ftp://, sftp://, ldap://, smb://.

auth plugins

These are authentication plugins. They are loaded automatically by the Connector/C when the server requests a specific authentication method.

mysql_native_password

dialog

This is a generic dialog plugin that asks the user a question (as instructed by the server) and sends the answer to the server. Everything is sent in plain text, one should enable SSL if secrets are sent via this plugin. Graphical clients can customize the plugin to provide graphical dialog form. See

client_ed25519

caching_sha2_password

sha256_password

auth_gssapi_client

mysql_old_password

mysql_clear_password

Prerequisites For Building Connector/C From Source

Building MariaDB Connector/C from source requires CMake, a C compiler, and TLS/SSL libraries. Windows needs Visual Studio; Linux and macOS need gcc with optional Curl or Kerberos.

Windows

  • Visual Studio 2013 or newer (older versions of Visual Studio may also work but have not been tested).

  • cmake 3.12.0 or newer, available from the CMake website.

  • for Connector/C 2.x: OpenSSL libraries and include files.

  • for Connector/C 3.0 remote-io plugin: Curl libraries and include files

Linux / Mac OS X

The following is a list of tools that are required for building MariaDB Connector/C on Linux and Mac OS X. Most, if not all, of these will exist as packages in your distribution's package repositories, so check there first.

  • gcc 3.4.6 or newer C compiler

  • TLS/SSL libraries and include files

    • OpenSSL 1.0.1 or newer or

    • GnuTLS 3.4.2 or newer

  • cmake 3.12.0 or newer, available from the .

  • for Connector/C 3.0 remote-io plugin: libraries and include files

  • For GSSAPI plugin: libraries

On Linux you can get those programs with your package manager. On Mac OS X you will need Xcode and to install the remaining programs with Fink or MacPorts.

Compiling Connector/C

Compile MariaDB Connector/C after configuration using CMake on Windows or Unix. Supports Visual Studio builds and GNU make, with both IDE and command-line build options.

After successful configuration, Connector/C can now be compiled.

Compiling on Windows

If no CMake generator was specified, CMake creates by default build files for Visual Studio. You can now either build Connector/C inside Visual Studio

devenv mariadb_connector_c.sln

or via command line

cmake --build . --config RelWithDebInfo

Compiling on Unix

By default CMake creates build files for GNU make. On some system GNU make is renamed to gmake. You can now build Connector/C with

make

or

cmake --build . --config Release

mariadb_cancel

mariadb_cancel immediately aborts a connection by making all subsequent read/write operations fail, without freeing the MYSQL structure or closing communication channels.

Syntax

int mariadb_cancel(MYSQL * mysql);

Parameter

  • mysql - mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Immediately aborts a connection by making all subsequent read/write operations fail.mariadb_cancel() does not invalidate memory used for mysql structure, nor close any communication channels. To free the memory, mysql_close() must be called.mariadb_cancel() is useful to break long queries in situations where sending KILL is not possible.

Return Value

Returns zero on success or a non-zero value on error.

History

mariadb_cancel() was added in Connector/C 3.0

mariadb_field_attr

Syntax

#include <mysql.h>

int mariadb_field_attr(MARIADB_CONST_STRING *attr,
                        const MYSQL_FIELD *field,
                        enum mariadb_field_attr_t type)

Parameter

  • attr: A pointer which returns extended metadata information

  • field: Specifies the field which contains extended metadata information

  • type: Specifies type of metadata information. Supported types are MARIADB_FIELD_ATTR_DATA_TYPE_NAME and MARIADB_FIELD_ATTR_FORMAT_NAME.

Returns extended metadata information for pluggable field types like JSON and GEOMETRY.

Returns zero on success or non zero if the field doesn't provide extended metadata information.

  • Pluggable field type support is available in MariaDB server version 10.5.2 and later.

  • To check if the server supports pluggable field types, check the extended server capabilities which can be obtained by api function .

mariadb_field_attr was added in MariaDB Connector/C 3.1.8.

mariadb_reconnect

mariadb_reconnect attempts to re-establish a dropped MariaDB Connector/C connection using the original credentials, and requires the MYSQL_OPT_RECONNECT option to be set.

Syntax

my_bool  mariadb_reconnect(MYSQL * mysql)

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

mariadb_reconnect() tries to reconnect to a server in case the connection died due to timeout or other errors. It uses the same credentials which were specified in mysql_real_connect().

Return Value

The function will return 0 on success. The function will return an error, if the option MYSQL_OPT_RECONNECT wasn't specified before.

History

This function was added in Connector/C 3.0.

See Also

  • mysql_real_connect()

  • mysql_options()

mysql_affected_rows

mysql_affected_rows returns the number of rows affected by the last INSERT, UPDATE, DELETE, or REPLACE statement executed on a MariaDB Connector/C connection.

Syntax

my_ulonglong mysql_affected_rows(MYSQL * mysql);

Parameter

  • mysql is a connection identifier, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns the number of affected rows by the last operation associated with MySQL, if the operation was an "upsert" (, , or ) statement, or UINT64_MAX (0xffffffffffffffff) if the last query failed.

When using , MariaDB will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

The statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records in addition to the number of inserted records.

Return Value

Returns the number of affected rows or -1 on error.

See Also

  • mysql_num_rows()

mysql_autocommit

mysql_autocommit enables or disables autocommit mode for the current database connection, returning zero on success or nonzero on failure.

Syntax

my_bool mysql_autocommit(MYSQL * mysql, my_bool auto_mode);

Parameters

  • mysql - a mysql handle, identifier, which was previously allocated by mysql_init() or mysql_real_connect().

  • auto_mode - whether to turn on or not.

Description

Toggles autocommit mode on or off for the current database connection. Autocommit mode will be set if mode=1 or unset if mode=0.

Return Value

Returns zero on success, or nonzero if an error occurred.

mysql_change_user

mysql_change_user changes the authenticated user and default database on an existing connection, resetting session state including transactions, temporary tables, and locks.

Syntax

my_bool mysql_change_user(MYSQL * mysql,
                          const char * user,
                          const char * passwd,
                          const char * db);
  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

  • user - the user name for server authentication

  • passwd - the password for server authentication

  • db - the default database. If desired, the NULL value may be passed resulting in only changing the user and not selecting a database. To select a database in this case use the mysql_select_db() function.

Description

Changes the user and default database of the current connection.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

Return Value

Returns zero on success, nonzero if an error occurred.

mysql_change_user will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

See Also

  • mysql_real_connect()

  • mysql_select_db()

mysql_character_set_name

mysql_character_set_name returns the name of the default client character set for a specified MariaDB Connector/C connection.

Syntax

const char * mysql_character_set_name(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns the default client for the specified connection.

Return value

The character set name used for the specified connection.

This function is deprecated. Instead, use mariadb_get_infov() with option MARIADB_CONNECTION_CHARSET_INFO.

See Also

  • mysql_set_character_set()

mysql_close

mysql_close terminates an open database connection and releases the memory allocated for the MYSQL handle.

Syntax

void mysql_close(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Closes a previously opened connection and deallocates all memory.

To reuse a connection handle after mysql_close() the handle must be initialized again by mysql_init().

See Also

  • mysql_init()

  • mysql_real_connect()

mysql_commit

mysql_commit commits the current transaction on a MariaDB Connector/C connection, returning zero on success without affecting autocommit mode.

Syntax

my_bool mysql_commit(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Commits the current transaction for the specified database connection.

Return Value

Returns zero on success, nonzero if an error occurred.

Executing mysql_commit() will not affected the behaviour of . This means, any update or insert statements following mysql_commit() will be rolled back when the connection gets closed.

See Also

  • mysql_rollback()

  • mysql_autocommit()

mysql_data_seek

mysql_data_seek moves the result set pointer to an arbitrary row offset in a buffered result set obtained via mysql_store_result, enabling random row access.

Syntax

void mysql_data_seek(MYSQL_RES * result,
                     my_ulonglong offset);

Parameters

  • result - a result set identifier returned by mysql_store_result().

  • offset - the field offset. Must be between zero and the total number of rows minus one (0..mysql_num_rows - 1).

Description

The mysql_data_seek() function seeks to an arbitrary function result pointer specified by the offset in the result set.

This function can only be used with buffered result sets obtained from the use of the function.

See Also

  • mysql_num_rows()

  • mysql_store_result()

mysql_dump_debug_info

mysql_dump_debug_info instructs a MariaDB server to write connection status information to the error log, and requires the SUPER privilege for the current user.

Syntax

int mysql_dump_debug_info(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

This function is designed to be executed by an user with the SUPER privilege and is used to dump server status information into the log for the MariaDB Server relating to the connection.

Return Value

Returns zero on success, nonzero if an error occurred.

The server status information will be dumped into the file, which can usually be found in the data directory of your server installation.

See Also

  • mysql_debug()

  • mysql_debug_end()

mysql_errno

mysql_errno returns the numeric error code from the most recent MariaDB Connector/C function call, or zero if no error occurred.

Syntax

unsigned int mysql_errno(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns the last for the most recent function call that can succeed or fail. Zero means no error occurred.

Client error messages are listed in errmsg.h header file, server error messages are listed in mysqld_error.h header file of the server source distribution.

See Also

  • mysql_error()

  • mysql_sqlstate()

mysql_error

mysql_error returns the error message string for the most recent failed MariaDB Connector/C function call, or an empty string if no error occurred.

Syntax

const char * mysql_error(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns the last error message for the most recent function call that can succeed or fail. If no error occurred an empty string is returned.

  • Client error codes are listed in errmsg.h header file, server error codes are listed in mysqld_error.h header file of the server source distribution.

  • Client error messages can be obtained by calling mariadb_get_infov() and passing the parameter MARIADB_CLIENT_ERRORS

See Also

  • mysql_errno()

  • mysql_sqlstate().

mysql_escape_string

mysql_escape_string encodes a string using the default character set for safe use in SQL statements. Deprecated — use mysql_real_escape_string instead.

Syntax

unsigned long mysql_escape_string(char * to,
                                  const char * from,
                                  unsigned long);

Description

Escapes a string using the default character set.

This function is deprecated and will be discontinued. Please use mysql_real_escape_string() instead.

See Also

  • mysql_real_escape_string()

mysql_fetch_field

mysql_fetch_field returns the definition of one result set column as a MYSQL_FIELD pointer; call it repeatedly to iterate over all columns in the result set.

Syntax

MYSQL_FIELD * mysql_fetch_field(MYSQL_RES * result);

Parameter

  • result - a result set identifier returned by mysql_store_result() or mysql_use_result().

Description

Returns the definition of one column of a result set as a pointer to a MYSQL_FIELD structure. Call this function repeatedly to retrieve information about all columns in the result set.

Return Value

A pointer of a MYSQL_FIELD structure, or NULL if there are no more fields.

The field order will be reset if you execute a new SELECT query.

In case only information for a specific field is required the field can be selected by using the mysql_field_seek() function or obtained by mysql_fetch_field_direct() function.

See Also

  • mysql_field_seek()

  • mysql_field_tell()

  • mysql_fetch_field_direct()

  • mysql_store_result()

  • mysql_use_result()

mysql_fetch_field_direct

mysql_fetch_field_direct returns a MYSQL_FIELD pointer for a specific column in a result set, identified by its zero-based field number.

Syntax

MYSQL_FIELD * mysql_fetch_field_direct(MYSQL_RES * res,
                                       unsigned int fieldnr);

Parameters

  • res - a result set identifier returned by mysql_store_result() or mysql_use_result().

  • fieldnr - the field number. This value must be within the range from 0 to number of fields - 1

Description

Returns a pointer to a MYSQL_FIELD structure which contains field information from the specified result set.

Return Value

Pointer to a MYSQL_FIELD structure. The caller must ensure that fieldnr is less than mysql_field_count(); specifying an out-of-range value results in undefined behavior, not a NULL return.

The total number of fields can be obtained by mysql_field_count().

See Also

  • mysql_fetch_field()

  • mysql_field_count()

mysql_fetch_fields

mysql_fetch_fields returns all column definitions for a MariaDB result set as an array of MYSQL_FIELD structures, one entry per column.

Syntax

MYSQL_FIELD * mysql_fetch_fields(MYSQL_RES * res);

Parameter

  • res - a result set identifier returned by mysql_store_result() or mysql_use_result().

Description

This function serves an identical purpose to the mysql_fetch_field() function with the single difference that instead of returning one field at a time for each field, the fields are returned as an array. Each field contains the definition for a column of the result set.

Return Value

An array of type MYSQL_FIELD.

The total number of fields can be obtained by mysql_field_count().

See Also

  • mysql_fetch_field()

  • mysql_fetch_field_direct()

  • mysql_field_count()

mysql_fetch_lengths

mysql_fetch_lengths returns an array of byte lengths for each column in the current row of a MariaDB result set, valid only after mysql_fetch_row is called.

Syntax

unsigned long * mysql_fetch_lengths(MYSQL_RES * result);

Parameter

  • result - a result set identifier returned by mysql_store_result() or mysql_use_result().

Description

The mysql_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set (not including terminating zero character) or NULL if an error occurred.

Return Value

An array of unsigned long values . The size of the array can be determined by the number of fields in current result set.

mysql_fetch_lengths() is valid only for the current row of the result set. It returns NULL if you call it before calling mysql_fetch_row() or after retrieving all rows in the result.

See Also

  • mysql_fetch_row()

  • mysql_field_count()

mysql_fetch_row

mysql_fetch_row retrieves the next row from a MariaDB result set as an array of char pointers, returning NULL when no more rows are available.

Syntax

MYSQL_ROW mysql_fetch_row(MYSQL_RES * result);

Parameter

  • result - a result set identifier returned by mysql_store_result() or mysql_use_result().

Description

Fetches one row of data from the result set and returns it as an array of char pointers (MYSQL_ROW), where each column is stored in an offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.

If a column contains a NULL value the corresponding char pointer will be set to NULL.

Memory associated to MYSQL_ROW will be freed when calling mysql_free_result() function.

See Also

  • mysql_use_result()

  • mysql_store_result()

mysql_field_count

mysql_field_count returns the number of columns in the most recent query result for a MariaDB connection, useful for checking whether a result set is available.

Syntax

unsigned int mysql_field_count(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns the number of columns for the most recent query on the connection represented by the link parameter as an unsigned integer. This function can be useful when using the mysql_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Return Value

The number of columns for the most recent statement. The value is zero, if the statement didn't produce a result set.

The mysql_field_count() function should be used to determine if there is a result set available.

See Also

  • mysql_store_result()

  • mysql_use_result()

mysql_field_seek

mysql_field_seek sets the field cursor to a given column offset in a MariaDB result set, controlling which field mysql_fetch_field returns next.

Syntax

MYSQL_FIELD_OFFSET mysql_field_seek(MYSQL_RES * result,
                                    MYSQL_FIELD_OFFSET offset);

Parameters

  • result - a result set identifier returned by mysql_store_result() or mysql_use_result().

  • offset - the field number. This number must be in the range from 0..number of fields - 1.

Description

Sets the field cursor to the given offset. The next call to mysql_fetch_field() will retrieve the field definition of the column associated with that offset.

Return Value

Returns the previous value of the field cursor.

  • The number of fields can be obtained from .

  • To move the field cursor to the first field offset parameter should be null.

See Also

  • mysql_field_tell()

mysql_field_tell

mysql_field_tell retrieves the current field cursor position in a result set, which can be passed to mysql_field_seek to restore that position.

Syntax

MYSQL_FIELD_OFFSET mysql_field_tell(MYSQL_RES * result);

Parameter

  • result - a result set identifier returned by mysql_store_result() or mysql_use_result().

Description

Return the offset of the field cursor used for the last mysql_fetch_field() call. This value can be used as a parameter for the function mysql_field_seek().

Return Value

Returns the current offset of the field cursor

See Also

  • mysql_field_seek()

mysql_free_result

mysql_free_result releases the memory allocated for a MariaDB result set; row values obtained from prior mysql_fetch_row calls become invalid after this call.

Syntax

void mysql_free_result(MYSQL_RES * result);

Parameter

  • result - a result set identifier returned by mysql_store_result() or mysql_use_result().

Description

Frees the memory associated with a result set.

Return Value

Returns void.

  • You should always free your result set with mysql_free_result() as soon it's not needed anymore

  • Row values obtained by a prior mysql_fetch_row() call will become invalid after calling mysql_free_result().

See Also

  • mysql_store_result()

  • mysql_use_result()

mysql_get_character_set_info

mysql_get_character_set_info populates a MY_CHARSET_INFO structure with details about the current default character set for a MariaDB Connector/C connection.

Syntax

void mysql_get_character_set_info(MYSQL * mysql,
                                  MY_CHARSET_INFO * charset);

Parameters

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

  • charset - a pointer to a MY_CHARSET_INFO structure, in which the information will be copied.

Returns information about the current default for the specified connection.

mysql_get_client_info

mysql_get_client_info retrieves the client library version as a string; use mysql_get_client_version for the equivalent numeric value.

Syntax

const char * mysql_get_client_info(void );

Description

Returns a string representing the client library version

To obtain the numeric value of the client library version use mysql_get_client_version().

See Also

  • mysql_get_client_version()

  • mysql_get_host_info()

  • mysql_get_proto_info()

mysql_get_client_version

mysql_get_client_version retrieves the client library version as an unsigned long; use mysql_get_client_info for the string representation.

Syntax

unsigned long mysql_get_client_version(void);

Description

Returns a number representing the client library version. The value has the format XXYYZZ: major version * 10000 + minor version * 100 + patch version.

Return Value

A long integer representing the client version

  • To obtain a string containing the client library version use the mysql_get_client_info() function.

  • Since MariaDB Server 10.2.6 and MariaDB Connector/C 3.0.1 the client library is bundled with server package and returns the server package version. To obtain the client version of the connector, please use the constant MARIADB_PACKAGE_VERSION_ID

See Also

  • mysql_get_client_info()

mysql_get_host_info

mysql_get_host_info returns a string describing the connection type and server hostname for a MariaDB Connector/C connection, or NULL if invalid.

Syntax

char * mysql_get_host_info(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Describes the type of connection in use for the connection, including the server host name.

Return Value

Returns a string, describing host information or NULL if the connection is not valid.

See Also

  • mysql_get_server_version()

mysql_get_proto_info

mysql_get_proto_info returns the protocol version number used for a MariaDB Connector/C connection; versions 9 and below are not supported.

Syntax

unsigned int mysql_get_proto_info(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns the protocol version number for the specified connection.

Return Value

The protocol version number in use.

The client library doesn't support protocol version 9 and prior.

See Also

  • mysql_get_host_info()

mysql_get_server_info

mysql_get_server_info retrieves the connected server version string; use mysql_get_server_version for the equivalent numeric representation.

Syntax

char * mysql_get_server_info(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns the server version or NULL on failure.

Return Value

Returns the server version as zero terminated string or NULLon failure.

To obtain the numeric server version please use .

See Also

mysql_get_server_version

mysql_get_server_version retrieves the server version as an unsigned long; use mysql_get_server_info for the equivalent string representation.

Syntax

unsigned long mysql_get_server_version(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns an integer representing the version of connected server.

Return Value

The version number of the connected server.

The form of the version number is VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH

See Also

  • mysql_get_server_info()

mysql_get_ssl_cipher

mysql_get_ssl_cipher returns the name of the TLS cipher in use for a MariaDB Connector/C connection, or NULL for non-TLS connections.

Syntax

const char *mysql_get_ssl_cipher(MYSQL *mysql)

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Returns the name of the currently used cipher of the , or NULL for non TLS connections.

Return Value

Returns a zero terminated string containing the cipher suite used for a secure connection, or NULL if connection doesn't use TLS/SSL.

Notes

  • For using mysql_get_ssl_cipher() MariaDB Connector/C must be built with TLS/SSL support, otherwise the function will return NULL.

  • `mysql_get_ssl_cipher()' can be used to determine if the client server connection is secure.

  • Depending on the TLS library in use (OpenSSL, GnuTLS or Windows Schannel) the name of the cipher suites may differ. For example the cipher suite 0x002F (TLS_RSA_WITH_AES_128_CBC_SHA) has different names: AES128-SHA for OpenSSL and Schannel and TLS_RSA_AES_128_CBC_SHA1 for GnuTLS.

See Also

  • mysql_ssl_set()

mysql_get_timeout_value

Syntax

#include <mysql.h>

unsigned int mysql_get_timeout_value(const MYSQL *mysql);

Parameter

Parameter
Description

mysql

A connection handle previously allocated by mysql_init() and connected by mysql_real_connect().

Description

mysql_get_timeout_value retrieves the current timeout value configured for asynchronous operations on the given connection, expressed in seconds.

Return Value

The timeout value in seconds as an unsigned int.

This function is deprecated. Use with the MARIADB_CONNECTION_ASYNC_TIMEOUT option instead.

See Also

  • mysql_get_timeout_value_ms()

  • mariadb_get_infov()

mysql_get_timeout_value_ms

Syntax

#include <mysql.h>

unsigned int mysql_get_timeout_value_ms(const MYSQL *mysql);

Parameter

Parameter
Description

mysql

A connection handle previously allocated by mysql_init() and connected by mysql_real_connect().

Description

mysql_get_timeout_value_ms retrieves the current timeout value configured for asynchronous operations on the given connection, expressed in milliseconds.

Return Value

The timeout value in milliseconds as an unsigned int.

This function is deprecated. Use with the MARIADB_CONNECTION_ASYNC_TIMEOUT option instead.

See Also

  • mysql_get_timeout_value()

  • mariadb_get_infov()

mysql_hex_string

mysql_hex_string converts a binary buffer to a hex-encoded string for safe embedding in SQL; the output buffer must be at least 2*length+1 bytes.

Syntax

unsigned long mysql_hex_string(char * to,
                               const char * from,
                               unsigned long len);

Parameters

  • to - result buffer

  • from - the string which will be encoded

  • len - length of the string (from)

Description

This function is used to create a hexadecimal string which can be used in SQL statements. e.g. INSERT INTO my_blob VALUES(X'A0E1CD').

Return Value

Returns the length of the encoded string without the trailing null character.

  • The size of the buffer for the encoded string must be 2 * length + 1.

  • The encoded string does not contain a leading X'.

See Also

  • mysql_real_escape_string()

mysql_info

mysql_info returns a string with summary statistics about the last executed query, covering INSERT, UPDATE, ALTER TABLE, and LOAD DATA operations; returns NULL for SELECT.

Syntax

const char * mysql_info(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

The mysql_info() function returns a string providing information about the last query executed.

Return Value

Possible mysql_info return values. The nature of this string is provided below:

Query type
Example result string

mysql_init

mysql_init allocates and initializes a MYSQL structure for use with mysql_real_connect, and also initializes the thread subsystem if not already done.

Syntax

MYSQL * mysql_init(MYSQL * mysql);

Parameter

  • mysql - a pointer to MYSQL or NULL. In case of passing a NULL pointer mysql_init() will allocate memory and return a pointer to a MYSQL structure.

Description

Prepares and initializes a MYSQL structure to be used with mysql_real_connect().

mysql_init() also ensures the client library is initialized, via a one-time internal initialization; it does not depend on mysql_thread_init(), which is a no-op retained for compatibility.

Return Value

The mysql_init() function returns an address of a MYSQL structure, or NULL in case of memory allocation error.

Members of the MYSQL structure are not intended for application use.

Any subsequent calls to any mysql function (except mysql_options()) will fail until was called.

Memory allocated by mysql_init() must be freed with .

See Also

  • mysql_real_connect()

  • mysql_options()

  • mysql_thread_init()

  • mysql_close()

mysql_insert_id

mysql_insert_id returns the AUTO_INCREMENT value generated by the last INSERT or UPDATE statement on a MariaDB connection, or zero if no such value was produced.

Syntax

my_ulonglong mysql_insert_id(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

The mysql_insert_id() function returns the ID generated by a query on a table with a column having the attribute or the value for the last usage of . If the last query wasn't an or statement or if the modified table does not have a column with the attribute and was not used, this function will return zero.

Return Value

Returns the value of the modified column with AUTO_INCREMENT attribute. If the table doesn't contain an auto_increment column or no INSERT/UPDATE statement was executed, this function will return zero.

When performing a multi-insert statement, mysql_insert_id() will return the value of the first row.

See Also

  • mysql_stmt_insert_id()

mysql_kill

mysql_kill requests the MariaDB server to terminate the thread with the given process ID; use mysql_thread_id to obtain the ID of the current connection.

Syntax

int mysql_kill(MYSQL * mysql,
               unsigned long pid);

Parameters

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

  • unsigned long - process id

Description

This function is used to ask the server to kill a MariaDB thread specified by the processid parameter. This value must be retrieved by . If trying to kill the own connection mysql_thread_id() should be used.

Return Value

Returns 0 on success, otherwise error on nonzero.

  • To stop a running command without killing the connection, use .

  • The mysql_kill() function only kills a connection; it doesn't free any memory - this must be done explicitly by calling .

See Also

  • mysql_thread_id()

  • mysql_close()

  • mariadb_cancel()

mysql_load_plugin

Syntax

#include <mysql.h>

struct st_mysql_client_plugin *
mysql_load_plugin(struct st_mysql *mysql, const char *name, int type,
                  int argc, ...);

Parameters

Parameter
Description

mysql

A connection handle previously allocated by and connected by .

name

The name of the plugin to load.

mysql_load_plugin searches the client plugin directory for a plugin matching the given name and type, loads it, and calls its initialization function with any supplied arguments. If a plugin with that name is already loaded, the call fails and returns NULL (error "it is already loaded").

  • MYSQL_CLIENT_AUTHENTICATION_PLUGIN

  • MARIADB_CLIENT_PVIO_PLUGIN

  • MARIADB_CLIENT_REMOTEIO_PLUGIN

A pointer to the plugin handle, or NULL if an error occurred.

mysql_library_end

mysql_library_end finalizes the MariaDB Connector/C library after use, performing memory cleanup and shutting down the embedded server if applicable.

Syntax

void mysql_library_end(void)

Description

Call when finished using the library, such as after disconnecting from the server. In an embedded server application, the embedded server is shut down and cleaned up. For a client program, only cleans up by performing memory management tasks.

mysql_server_end() is an alias.

See Also

  • mysql_library_init()

mysql_library_init

mysql_library_init initializes the MariaDB Connector/C library before any other functions are called, starting the embedded server if used in that configuration.

Syntax

int mysql_library_init(int argc, char **argv, char **groups)

Description

Call to initialize the library before calling other functions, both for embedded servers and regular clients. If used on an embedded server, the server is started and subsystems initialized. Returns zero for success, or nonzero if an error occurred.

Call mysql_library_end() to clean up after completion.

mysql_server_init() is an alias.

See Also

  • mysql_library_end()

mysql_more_results

mysql_more_results indicates whether additional result sets remain from a previous multi-statement query, returning 1 if more results are available.

Syntax

my_bool mysql_more_results(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Indicates if one or more result sets are available from a previous call to mysql_real_query().

Return Value

Returns 1 if more result sets are available, otherwise zero..

  • The function mysql_set_server_option() enables or disables multi statement support.

  • Multiple result sets can be obtained either by calling a stored procedure or by executing concatenated statements, e.g. SELECT a FROM t1;SELECT b, c FROM t2.

See Also

  • mysql_real_query()

  • mysql_use_result()

  • mysql_store_result()

  • mysql_next_result()

mysql_next_result

mysql_next_result advances to the next result set from a multi-statement query, making it available for retrieval via mysql_store_result or mysql_use_result.

Syntax

int mysql_next_result(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Prepares next result set from a previous call to mysql_real_query() which can be retrieved by mysql_store_result() or mysql_use_result().

Return Value

Returns zero on success, nonzero if an error occurred.

If a multi query contains errors the return value of /error() might change and there will be no result set available.

See Also

mysql_num_fields

mysql_num_fields retrieves the column count from a result set handle, useful for iterating over fields in a MariaDB query result.

Syntax

unsigned int mysql_num_fields(MYSQL_RES * );

Parameter

  • MYSQL RES * - A result set identifier returned by mysql_store_result() or mysql_use_result().

Description

Returns number of fields in a specified result set.

Return Value

Returns number of fields.

See Also

  • mysql_fetch_field()

  • mysql_field_count()

mysql_num_rows

mysql_num_rows returns the number of rows in a MariaDB result set; for unbuffered results the count is only accurate after all rows have been fetched.

Syntax

my_ulonglong mysql_num_rows(MYSQL_RES * );

Parameter

  • MYSQL_RES - a result set identifier returned by mysql_store_result() or mysql_use_result().

Description

Returns number of rows in a result set.

The behavior of mysql_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysql_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved.

See Also

  • mysql_affected_rows()

  • mysql_use_result()

  • mysql_store_result()

mysql_options4

Syntax

#include <mysql.h>

int mysql_options4(MYSQL *mysql,
                   enum mysql_option option,
                   const void *arg1,
                   const void *arg2);

Parameters

Parameter
Description

mysql

A connection handle previously allocated by mysql_init(). Must be called before mysql_real_connect().

option

The option to set.

arg1

The first value for the option.

arg2

The second value for the option.

Description

mysql_options4 is used to set extra connect options and affect behavior for a connection. This function may be called multiple times to set several options. It must be called after mysql_init() and before mysql_real_connect().

Return Value

Returns zero on success, non-zero if the option is unknown or the value is invalid.

Options

An overview of the possible options can be found in the description of the mysql_optionsv() API function.

This function is deprecated, new implementations should use api function instead.

See Also

  • mysql_optionsv()

  • mysql_options()

  • mysql_real_connect()

mysql_options

mysql_options sets extra connection options on a MYSQL handle before calling mysql_real_connect. Deprecated since Connector/C 3.0 — use mysql_optionsv instead.

Syntax

int mysql_options(MYSQL * mysql,
                  enum mysql_option,
                  const void * arg);

Parameters

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

  • mysql_option - the option you want to set. See description below.

  • arg - the value for the option.

Used to set extra connect options and affect behavior for a connection. This function may be called multiple times to set several options. mysql_options() should be called after and before .

Returns zero on success, non zero if an error occurred (invalid option or value).

See .

mysql_ping

mysql_ping checks whether a MariaDB server connection is still active and attempts an automatic reconnect if the connection has dropped and reconnect is enabled.

Syntax

int mysql_ping(MYSQL * mysql);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

Description

Checks whether the connection to the server is working. If it has gone down, and global option reconnect is enabled an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Return Value

Returns zero on success, nonzero if an error occurred.

If a reconnect occurred the thread_id will change. Also resources bundled to the connection (prepared statements, locks, temporary tables, ...) will be released.

See Also

mysql_query

mysql_query sends a null-terminated SQL string to the MariaDB server for execution, returning zero on success; use mysql_real_query for binary-safe operation.

Syntax

int mysql_query(MYSQL * mysql,
                const char * query);

Parameters

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

  • query -a null terminated string containing the statement to be performed.

Description

Performs a statement pointed to by the null terminate string query against the database. Contrary to mysql_real_query(), mysql_query() is not binary safe.

Returns zero on success, non zero on failure

Allocates and initializes a replication handle

mariadb_rpl_optionsv()

Sets options on a replication handle

mariadb_rpl_get_optionsv()

Retrieves the current value of a replication handle option

mariadb_rpl_open()

Opens a binary log stream and registers the client as a replica

mariadb_rpl_fetch()

Fetches the next event from a binary log stream

mariadb_free_rpl_event()

Frees memory allocated for an event

mariadb_rpl_extract_rows()

Extracts a list of rows from a row event

mariadb_rpl_errno()

Returns the error number for the last Binlog API call

mariadb_rpl_error()

Returns the error message for the last Binlog API call

mariadb_rpl_close()

Closes a binary log stream and frees the replication handle

See Also

MariaDB Binlog/Replication API Reference
Replication API Types and Definitions
Replication API Function Reference
mariadb_rpl_init()

MARIADB_CLIENT_CONNECTION_PLUGIN or MARIADB_CLIENT_COMPRESSION_PLUGIN.

type

The plugin type, or -1 to accept any type.

argc

The number of optional arguments that follow.

...

Optional arguments passed to the plugin's initialization function.

Description

Valid Plugin Types

Return Value

  • If the type of the plugin is not known, -1 needs to be specified for parameter type.

  • The directory which contains the plugin can be specified either by the environment variable MARIADB_PLUGIN_DIR or it can be specified with mysql_optionsv() using the option MYSQL_PLUGIN_DIR.

See Also

mysql_optionsv()
mysql_init()
mysql_real_connect()
mariadb_get_infov()
mariadb_get_infov()
mysql_optionsv()
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
CMake website
Curl
Kerberos V5
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
spinner
mysql_store_result
spinner
spinner
mysql_field_count()
spinner
spinner
mysql_real_connect()
mysql_close()
spinner
spinner

Description

Return Value

This function is deprecated as of MariaDB Connector/C 3.0 and will be removed in future releases. It's preferable to use mysql_optionsv.

Options

See Also

mysql_init()
mysql_real_connect()
mysql_optionsv
mysql_init()
mysql_optionsv
mysql_real_connect()
spinner
mysql_real_query()
mysql_store_result()
mysql_use_result()
mysql_more_results()
mysql_errno
spinner
mysql_get_server_version()
mysql_get_client_info()
mysql_get_server_version()
spinner

mysql_store_result()

Return Value

For executing multi statements the statements within the null terminated string statements must be separated by a semicolon.

If your statement contains binary data you should use mysql_real_query() or escape your data with mysql_hex_string().

To determine if a statement returned a result set use the function mysql_num_fields().

See Also

mysql_real_query()
mysql_num_fields()
mysql_hex_string()
mysql_use_result()
spinner
mysql_options()
mysql_kill()
spinner

Description

Return Value

Notes

Example

History

See Also

mariadb_get_info()
mysql_store_result()
mysql_use_result()
mariadb_get_info()
mysql_fetch_fields()
#include <mysql.h>

int display_extended_field_attribute(MYSQL *mysql)
{
  MYSQL_RES *result;
  MYSQL_FIELD *fields;

  if (mysql_query(mysql, "CREATE TEMPORARY TABLE t1 (a POINT)"))
    return 1;

  if (mysql_query(mysql, "SELECT a FROM t1"))
    return 1;

  if (!(result= mysql_store_result(mysql)))
    return 1;

  if ((fields= mysql_fetch_fields(result)))
  {
    MARIADB_CONST_STRING field_attr;

    if (!mariadb_field_attr(&field_attr, &fields[0],
                            MARIADB_FIELD_ATTR_DATA_TYPE_NAME))
    {
      printf("Extended field attribute: %s\n", field_attr.str);
    }
  }
  mysql_free_result(result);
  return 0;
}

MARIADB_RPL_SERVER_ID

uint32_t *

Configured server ID.

MARIADB_RPL_FLAGS

uint32_t *

Current flags bitmask.

MARIADB_RPL_SEMI_SYNC

uint32_t *

Semi-sync replication state: 1 = enabled, 0 = disabled. Added in Connector/C 3.3.6.

The option to be set, followed by one or more values.

...

A pointer to a variable of the appropriate type to receive the option value.

MARIADB_RPL_FILENAME

char **, size_t *

Pointer to the binary log filename and its length.

MARIADB_RPL_START

unsigned long *

Start position in the binary log.

Options

Return Value

History

See also

mariadb_rpl_optionsv()
mariadb_rpl_init()

Records: 3 Duplicates: 0 Warnings: 0

Rows matched: 40 Changed: 40 Warnings: 0

Records: 100 Duplicates: 0 Warnings: 0

Records: 3 Duplicates: 0 Warnings: 0

Records: 1 Deleted: 0 Skipped: 0 Warnings: 0

Queries which do not fall into one of the preceding formats are not supported (e.g. ). In these situations, mysql_info() will return NULL.

See Also

mysql_affected_rows()
mysql_warning_count()

spinner

...

The value for the option. The type varies by option; see the options table.

Option
Type
Description

MARIADB_RPL_FILENAME

char *

Name of the binary log file to open, and its length in bytes.

MARIADB_RPL_START

unsigned long

Binary log position from which to start reading.

Returns zero on success, non-zero on failure.

Added in .

  • mariadb_rpl_get_optionsv()

  • mariadb_rpl_open()

#include <mariadb_rpl.h>

int mariadb_rpl_optionsv(MARIADB_RPL *rpl,
                          enum mariadb_rpl_option option,
                          ...);

rpl

A replication handle previously allocated by mariadb_rpl_init().

option

Syntax

Parameters

mariadb_rpl_open()

The option to configure. See the options table below.

Options

Return Value

History

See also

# Turn off autocommit
SET AUTOCOMMIT=0;

# Retrieve autocommit
SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            0 |
+--------------+
static int test_autocommit(MYSQL *mysql)
{
  int rc;
  unsigned int server_status;
  
  /* Turn autocommit off */
  rc= mysql_autocommit(mysql, 0);
  if (rc)
    return rc; /* Error */

  /* If autocommit = 0 succeeded, the last OK packet updated the server status */
  rc= mariadb_get_infov(mysql, MARIADB_CONNECTION_SERVER_STATUS, &server_status);
  if (rc)
    return rc; /* Error */

  if (server_status & SERVER_STATUS_AUTOCOMMIT)
  {
    printf("Error: autocommit is on\n");
    return 1;
  }
  printf("OK: autocommit is off\n");
  return 0;
}

mode only affects operations on transactional table types. To determine the current state of autocommit mode use the SQL command SELECT @@autocommit. Be aware: the mysql_rollback() function will not work if autocommit mode is switched on.

Examples

SQL

MariaDB Connector/C

spinner

Description

A complete list of supported character sets in the client library is listed in the function description for mysql_set_character_set_info().

See Also

mariadb_get_infov()
mysql_set_character_set_info()
spinner
mysql_close()
spinner

Connector/Node.js Guide

Quickstart guide for MariaDB Connector/Node.js

Quickstart Guide: MariaDB Connector/Node.js

MariaDB Connector/Node.js is a client library that enables Node.js applications to connect and interact with MariaDB and MySQL databases. It's built natively in JavaScript and supports both Promise and Callback APIs, with the Promise API being the default and recommended approach. It is licensed under the LGPL.

1. Installation

The easiest way to install MariaDB Connector/Node.js is using npm (Node Package Manager):

npm install mariadb

2. Basic Usage (Promise API - Recommended)

The Promise API simplifies asynchronous operations with async/await. For optimal performance and resource management, it's recommended to use a connection pool.

a. Create a Connection Pool:

const mariadb = require('mariadb');
const pool = mariadb.createPool({
    host: 'localhost',
    port: 3306,
    user: 'your_username',
    password: 'your_password',
    database: 'your_database_name',
    connectionLimit: 5 // Adjust as needed
});

console.log("Connection pool created.");

Replace localhost, 3306, your_username, your_password, and your_database_name with your actual database details.

b. Perform Database Operations:

Here's an async function example to get a connection, execute queries, and release the connection back to the pool.

If you need compatibility with older Node.js database drivers (mysql, mysql2), you can use the Callback API.

  • Error Handling: Always include robust error handling (try...catch for Promises, if (err) for Callbacks) in your database interactions.

  • Parameterized Queries: Always use parameterized queries (e.g., WHERE status = ?, VALUES (?, ?)) to prevent SQL injection attacks.

MariaDB Connector/NET Guide

Quickstart guide for MysqlConnector for ADO.NET

Quickstart Guide: MariaDB Connector/NET (MySqlConnector)

MariaDB Connector/NET, also known as MySqlConnector, is an ADO.NET data provider that enables .NET applications to connect and interact with MariaDB and MySQL databases. It's written entirely in C# and offers high performance and features specific to MariaDB Server.

1. Overview and Features

MySqlConnector is licensed under the MIT License. It provides robust connectivity with features like:

  • Zero-configuration SSL: For MariaDB Server 11.4+.

  • Server Redirection Logic: Based on the latest MariaDB specification for MariaDB Server 11.3+.

  • Optimized SET NAMES handling: Avoids unnecessary commands for MariaDB Server 11.5+.

  • MariaDB GSSAPI Authentication: Support for secure authentication methods.

  • Asynchronous Operations: Fully supports async/await patterns for non-blocking database interactions.

The recommended way to install MySqlConnector is via NuGet.

a. Using NuGet Package Manager Console (in Visual Studio):

b. Using PackageReference (in your .csproj file):

This section provides C# examples for connecting to MariaDB and performing common database operations.

a. Connection String:

A connection string defines how your application connects to the database. Replace placeholder values with your actual database details.

b. Opening and Closing a Connection:

Always ensure connections are properly opened and closed. The using statement is recommended as it ensures the connection is disposed of correctly, even if errors occur.

c. Executing a SELECT Query:

Use MySqlCommand to define your SQL query and ExecuteReaderAsync to retrieve data.

d. Executing INSERT/UPDATE/DELETE Queries:

Use ExecuteNonQueryAsync for operations that do not return a result set (like INSERT, UPDATE, DELETE). Always use parameterized queries to prevent SQL injection vulnerabilities.

MariaDB Connector/C Guide

Quickstart Guide for Connector/C

MariaDB Connector/C Quickstart Guide

This guide will help you quickly get started with MariaDB Connector/C, the client library used to connect C/C++ applications to MariaDB and MySQL databases. It's LGPL licensed and is being integrated directly into MariaDB Server distributions.

Installation

MariaDB Connector/C is often distributed with MariaDB Server packages, but you can also install it separately.

Download Packages

You can download MariaDB Connector/C packages directly:

  • From the downloads page: Select your desired version from the main MariaDB Connector/C download page.

  • By product selection: Choose "C/C++ connector" as the Product on the MariaDB downloads page.

If you're using Linux, the simplest way to install MariaDB Connector/C is via your system's package manager. Your system needs to be configured to install from a MariaDB repository (version 10.2 or later).

You can set up your repository using:

  • MariaDB Corporation's .

  • MariaDB Foundation's MariaDB Repository Configuration Tool.

Install with yum/dnf (RHEL, CentOS, Fedora)

For RHEL, CentOS, Fedora, and similar distributions, use yum or dnf:

To install the shared library:

To install the development package (if you're building applications):

Install with apt-get (Debian, Ubuntu)

For Debian, Ubuntu, and similar distributions, use apt-get:

To install the shared library:

To install the development package (if you're building applications):

Install with zypper (SLES, OpenSUSE)

For SLES, OpenSUSE, and similar distributions, use zypper:

To install the shared library:

To install the development package (if you're building applications):

MariaDB Connector/C for Windows is distributed as MSI packages. The installation process is straightforward, with both 32-bit and 64-bit MSI packages available.

If you prefer to build from source, refer to the documentation.

MariaDB Connector/C provides an API that is compatible with MySQL Connector/C for MySQL 5.5.

You can find the function reference at:

An HTML version is also available for download in mariadb-client-doc.zip.

Similar to MariaDB Server, MariaDB Connector/C can read configuration options from client option groups in option files.

For detailed information, see .

Be aware of these potential limitations:

  • Double-to-string conversion for prepared statements may not work correctly.

  • Connector versions 3.0.7 and below do not support MySQL 8.0's default authentication protocol, caching_sha2_password. This should be supported in Connector/C 3.0.8 and above.

  • Report Bugs: If you encounter a bug, please report it via the .

  • Source Code: The source code is available on GitHub in the .

GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

For licensing questions, see the .

Connector/Ruby Guide

Quickstart guide for Connector/Ruby

Quickstart Guide: MariaDB Connector/Ruby (using mysql2 gem)

While there isn't a separate "MariaDB Connector/Ruby" gem, the widely used mysql2 gem serves as the primary and highly compatible Ruby client for connecting to both MariaDB and MySQL databases. It provides a robust API for database interactions in Ruby applications.

1. Overview

The mysql2 gem provides a Ruby interface to the MariaDB/MySQL C client library (either libmysqlclient or MariaDB Connector/C). It allows Ruby applications to execute SQL queries, fetch results, and manage database connections efficiently. It's available on rubygems.org/gems/mysql2.

2. Installation

Before installing the mysql2 gem, you might need to install development libraries for MariaDB Connector/C or MySQL Client on your system.

a. Install System Dependencies (e.g., on Debian/Ubuntu):

On other systems (Fedora, CentOS, macOS), the package names might differ (e.g., mariadb-devel, mysql-devel).

b. Install the mysql2 gem:

Once the system dependencies are in place, install the gem using Bundler (recommended for Rails/Gemfile projects) or directly via gem install:

Here's how to connect to MariaDB and perform common database operations using the mysql2 gem:

a. Connect to the Database:

Replace localhost, 3306, your_username, your_password, and your_database_name with your actual database details.

b. Execute a SELECT Query:

The results object behaves like an enumerable, allowing you to iterate over rows. Column names are accessible as hash keys.

c. Execute INSERT/UPDATE/DELETE Queries:

For data manipulation, use query. For safety, always use prepared statements or proper escaping for user-provided input.

d. Prepared Statements (Recommended for security and performance):

Prepared statements allow you to separate the SQL query structure from the data, preventing SQL injection and improving performance for repeated queries.

Before Running:

  1. Ensure you have a MariaDB server running and a database/table set up.

  2. Replace placeholder values with your actual database credentials and table/column names.

  • Error Handling: Always wrap your database operations in begin...rescue...end blocks to catch Mysql2::Error exceptions.

  • Connection Closing: Ensure your Mysql2::Client connection is closed using client.close in a ensure block to release database resources.

Connector/ODBC Guide

Quickstart guide for MariaDB Connector/ODBC

Quickstart Guide: MariaDB Connector/ODBC

MariaDB Connector/ODBC is a database driver that allows applications to connect to MariaDB and MySQL databases using the Open Database Connectivity (ODBC) API. It's fully compliant with the ODBC 3.5 standard, open-source (LGPL), and can serve as a drop-in replacement for MySQL Connector/ODBC. It supports both Unicode and ANSI modes and communicates primarily using the MariaDB/MySQL binary protocol.

1. What is ODBC?

ODBC (Open Database Connectivity) is a standard API for accessing database management systems (DBMS). It provides a common way for applications to communicate with different databases, abstracting away the specifics of each database's native communication protocol. MariaDB Connector/ODBC acts as the specific bridge for MariaDB.

2. Installation

Installation typically involves downloading the appropriate driver package for your operating system and configuring a Data Source Name (DSN).

a. Windows:

  1. Download: Go to the and download the appropriate .msi installer for your Windows version (32-bit or 64-bit).

  2. Run Installer: Execute the downloaded .msi file and follow the on-screen instructions. This will install the necessary driver files.

  3. Configure DSN:

    • Open the ODBC Data Source Administrator:

      • For 64-bit systems, search for "ODBC Data Sources (64-bit)".

b. Linux / macOS:

  1. Download: Download the appropriate .deb, .rpm, or .pkg package from the .

  2. Install Package:

Once the MariaDB ODBC driver is installed and a DSN is configured, applications can connect to your MariaDB database using the standard ODBC API. The exact code will vary depending on the programming language and framework you are using (e.g., C++, Java with JDBC-ODBC Bridge, Python with pyodbc, PHP with odbc extension).

a. Connecting via DSN (Common for many applications):

Many applications and tools (like Microsoft Excel, reporting tools, or C++ applications using ODBC) will allow you to select a configured DSN directly.

b. Connecting via DSN-less Connection String:

You can also provide a full connection string directly in your application without pre-configuring a DSN. This is often used in scripting languages or when you need more dynamic control.

Replace {MariaDB ODBC Driver} with the exact driver name from your odbcinst.ini if different.

mysql_debug

mysql_debug enables debug output for a MariaDB Connector/C client using the DBUG library, accepting a colon-separated control string to configure trace and logging options.

Syntax

void mysql_debug(const char * debug);
  • debug - a string representing the debug operation to perform. See description below.

Description

Enables debug output for development and debug purposes by using Fred Fish's DBUG library. For using this function the mariadb-client library must be compiled with debug support.

Almost all MariaDB binaries use the DBUG library and one can get a trace of the program execution by using the command line option with the binary. This will only work if the binary is compiled for debugging (compiler option -DDBUG_ON).

Returns void.

The debug control string is a sequence of colon separated fields as follows:

Each field consists of a mandatory flag character followed by an optional "," and comma separated list of modifiers:

The currently recognized flag characters are:

Option
Description
  • mysql_debug_end()

mysql_get_optionv

mysql_get_optionv retrieves the current value of a connection option previously set with mysql_optionsv, supporting boolean, integer, string, and miscellaneous option types.

Syntax

int mysql_get_optionv(MYSQL * mysql,
                      enum mysql_option,
                      void * arg,
                      ...);
  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect().

  • mysql_option - the option you want to retrieve. See description below.

  • arg - pointer to a variable for storing value of the specified option.

  • ... - variable argument list

Retrieves the value for a given option which was previously set by .

Returns zero on success, non zero if an error occurred (invalid option).

This function was added in MariaDB Connector/C 3.0.0.

  • MYSQL_OPT_COMPRESS

  • MYSQL_OPT_NAMED_PIPE

  • MYSQL_OPT_RECONNECT

  • MYSQL_REPORT_DATA_TRUNCATION

  • MYSQL_OPT_CONNECT_TIMEOUT

  • MYSQL_OPT_READ_TIMEOUT

  • MYSQL_OPT_WRITE_TIMEOUT

  • MYSQL_OPT_LOCAL_INFILE

  • MYSQL_INIT_COMMAND

  • MYSQL_READ_DEFAULT_FILE

  • MYSQL_READ_DEFAULT_GROUP

  • MYSQL_SET_CHARSET_NAME

  • MYSQL_PLUGIN_DIR

  • MYSQL_PROGRESS_CALLBACK: requires a function pointer *(const MYSQL *, uint, uint, double, const char *, uint))arg)

  • MYSQL_CONNECT_ATTRS: this option requires 5 parameters:

  • MARIADB_OPT_USERDATA: retrieves userdata for a given key.

mariadb_get_infov

mariadb_get_infov retrieves generic or connection-specific information from a MariaDB Connector/C handle, accepting a value-type enum and a pointer to store the result.

Syntax

my_bool mariadb_get_infov(MYSQL * mysql,
                      enum mariadb_value value,
                      void * arg,
                      ...);

Parameter

  • mysql - a mysql handle, which was previously allocated by mysql_init() or mysql_real_connect(). For general information which is not bound to connection this parameter might be null.

  • value - the type of value you want to retrieve. See description below.

  • arg - pointer to a variable for storing value of the specified option.

  • ... - variable argument list

Retrieves generic or connection specific information. Returns zero on success, non-zero if an error occurred (invalid option), This function was added in MariaDB Connector/C 3.0,

For these information types of parameters mysql needs to be set to NULL.

  • MARIADB_CHARSET_NAME: Retrieves the charset information for a character set by its literal representation.Parameter type: const MARIADB_CHARSET_INFO*.

  • MARIADB_CLIENT_ERRORS: Retrieve array of client errors. This can be used in plugins to set global error messages (which are not exported by MariaDB Connector/C).Parameter type: const char **.

  • MARIADB_CONNECTION_ASYNC_TIMEOUT: Retrieves the timeout for non-blocking calls in seconds.Parameter type: unsigned int.

  • MARIADB_CONNECTION_ASYNC_TIMEOUT_MS: Retrieves the timeout for non-blocking calls in milliseconds.Parameter type: unsigned int.

Returns zero on success, non zero if an error occurred (e.g. if an invalid option was specified),

This function was added in MariaDB Connector/C 3.0,

MariaDB Connector/R2DBC Guide

Quickstart guide for MariaDB Connector/R2DBC

MariaDB Connector/R2DBC allows Java developers to connect to MariaDB and MySQL databases using the Reactive Relational Database Connectivity (R2DBC) API. This enables non-blocking, asynchronous database operations, which are beneficial for building scalable and responsive applications.

Add the necessary dependency to your project's pom.xml (Maven) or build.gradle (Gradle) file. Choose the dependency based on the R2DBC Specification you are targeting.

a. For R2DBC 1.0.0 Specification (Recommended for new projects):

XML

Gradle

b. For R2DBC 0.9.1 Specification (for compatibility):

Configuration Settings for Building Connector/C

Configure the MariaDB Connector/C build via CMake options including build type, TLS/SSL backend, install prefix, and client plugins such as authentication and connection handlers.

Connector/C specifies its build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists.txt. Configuration settings may be specified by passing the -D option to CMake command line interpreter.

Do not build Connector/C from the root of the source tree: Either create a subdirectory "build" inside the source tree or create a subdirectory outside of the source tree.

Example:

In case Connector/C was already configured, the CMakeCache.txt

MariaDB Connector/J Guide

Quickstart Guide for Connector/J

MariaDB Connector/J is the official Java Database Connectivity (JDBC) driver for connecting Java applications to MariaDB and MySQL databases. It allows Java programs to interact with databases using the standard JDBC API.

See for full content.

You can include MariaDB Connector/J in your project using build tools like Maven or Gradle, or by manually adding the JAR file to your project's classpath.

a. Using Maven:

Add the following dependency to your pom.xml file:

b. Using Gradle:

Add the following dependency to your build.gradle file:

spinner
spinner
spinner
spinner
spinner
spinner
spinner

Connection Pooling: For production applications, always use a connection pool (mariadb.createPool()) instead of single connections to manage resources efficiently.

  • conn.release() vs. conn.end(): When using a pool, use conn.release() to return the connection to the pool. Use conn.end() or pool.end() only when gracefully shutting down your application.

  • 3. Basic Usage (Callback API - for Compatibility)

    Important Notes:

    Further Resources:

    MariaDB Connector/Node.js GitHub Repository
    MariaDB Connector/Node.js Documentation
    npm mariadb package page

    2. Installation

    3. Basic Usage

    Prepared Statements/Escaping: Never concatenate user-provided strings directly into SQL queries. Use prepared statements with placeholders (?) or client.escape() for string literals.

    3. Basic Usage

    Important Notes:

    Further Resources:

    mysql2 gem on RubyGems.org
    mysql2 gem Documentation (Rubydoc.info)

    MYSQL_OPT_NONBLOCK

  • MYSQL_OPT_SSL_VERIFY_SERVER_CERT

  • MARIADB_OPT_CONNECTION_READ_ONLY

  • MYSQL_SECURE_AUTH

  • MYSQL_OPT_PROTOCOL

    MYSQL_OPT_SSL_KEY

  • MYSQL_OPT_SSL_CERT

  • MYSQL_OPT_SSL_CA

  • MYSQL_OPT_SSL_CAPATH

  • MYSQL_OPT_SSL_CRL

  • MYSQL_OPT_SSL_CRLPATH

  • MYSQL_OPT_SSL_CIPHER

  • MARIADB_OPT_SSL_FP

  • MARIADB_OPT_SSL_FP_LIST

  • MARIADB_OPT_SSL_PASSPHRASE

  • MYSQL_DEFAULT_AUTH

  • MYSQL_OPT_BIND

  • MARIADB_OPT_CONNECTION_HANDLER

  • Description

    Options

    Boolean values (my_bool)

    Integer values

    Character arrays

    Character values

    Misc

    See Also

    mysql_optionsv
    mysql_optionsv()
    spinner
    MARIADB_CLIENT_VERSION: The client version in literal representation.Parameter type: const char *.
  • MARIADB_CLIENT_VERSION_ID: The client version in numeric format.Parameter type: unsigned int.

  • MARIADB_MAX_ALLOWED_PACKET: Retrieves value of maximum allowed packet size.Parameter type: size_t

  • MARIADB_NET_BUFFER_LENGTH: Retrieves the length of net buffer.Parameter type: size_t

  • MARIADB_TLS_LIBRARY: The TLS library MariaDB Connector/C is compiled against.Parameter type: const char *.

  • MARIADB_CONNECTION_MARIADB_CHARSET_INFO: Retrieves character set information for given connection. Parameter type: const MY_CHARSET_INFO *.
  • MARIADB_CONNECTION_CLIENT_CAPABILITIES: Returns the capability flags of the client.Parameter type: unsigned long.

  • MARIADB_CONNECTION_ERROR: Retrieves error message for last used command. Parameter type: const char *.

  • MARIADB_CONNECTION_ERROR_ID: Retrieves error number for last used command. Parameter type: unsigned int.

  • MARIADB_CONNECTION_EXTENDED_SERVER_CAPABILITIES: Returns the extended capability flags of the connected MariaDB server.Parameter type: unsigned long.

  • MARIADB_CONNECTION_HOST: Retrieves connection's host name. Parameter type: const char *.

  • MARIADB_CONNECTION_INFO: Retrieves generic info for last used command.Parameter type: const char *.

  • MARIADB_CONNECTION_PORT: Retrieves the port number of server host.Parameter type: unsigned int.

  • MARIADB_CONNECTION_PROTOCOL_VERSION_ID: Retrieves the protocol version number.Parameter type: unsigned int.

  • MARIADB_CONNECTION_PVIO_TYPE: Retrieves the pvio plugin used for specified connection.Parameter type: unsigned int.

  • MARIADB_CONNECTION_SCHEMA: Retrieves the current schema.Parameter type: const char*.

  • MARIADB_CONNECTION_SERVER_CAPABILITIES: Returns the capability flags of the connected server.Parameter type: unsigned long.

  • MARIADB_CONNECTION_SERVER_STATUS: Returns server status after last operation. A list of possible flags can be found in the description OK packet.Parameter type: unsigned int.

  • MARIADB_CONNECTION_SERVER_TYPE: Retrieves the type of the server.Parameter type: const char*.

  • MARIADB_CONNECTION_SERVER_VERSION: Retrieves the server version in literal format.Parameter type: const char *.

  • MARIADB_CONNECTION_SERVER_VERSION_ID: Retrieves the server version in numeric format.Parameter type: unsigned int.

  • MARIADB_CONNECTION_SOCKET: Retrieves the handle (socket) for given connection.Parameter type: my_socket.

  • MARIADB_CONNECTION_SQLSTATE: Retrieves current sqlstate information for last used command. Parameter type: const char *.

  • MARIADB_CONNECTION_SSL_CIPHER: Retrieves the TLS cipher in use.Parameter type: const char *.

  • MARIADB_CONNECTION_TLS_VERSION: Retrieves the TLS protocol version used in literal format.Parameter type: char *.

  • MARIADB_CONNECTION_TLS_VERSION_ID: Retrieves the TLS protocol version used in numeric format.Parameter type: unsigned int.

  • MARIADB_CONNECTION_UNIX_SOCKET: Retrieves the file name of the unix socketParameter type: const char *.

  • MARIADB_CONNECTION_USER: Retrieves connection's user name.Parameter type: const char *.

  • MARIADB_TLS_PEER_CERT_INFO Retrieves peer certificate information for TLS connections. The returned pointer to a MARIADB_X509_INFO structure becomes invalid after the connection has been closed. (Added in version 3.4.0)

  • MARIADB_TLS_VERIFY_STATUS Retrieves the status of a previous peer certificate verification. The status is represented as a combination of TLS verification flags. This option was added in version 3.4.1

  • Description

    Value types

    Generic information

    Connection related information

    Return Value

    History

    Examples

    See Also

    mysql_get_optionv()
    spinner

    XML

    Gradle

    This example demonstrates how to establish a connection, execute a query, and process results using the reactive API.

    Code snippet

    Before Running:

    1. Replace your_username, your_password, your_database_name, and your_table_name with your actual MariaDB server details.

    2. Ensure you have a MariaDB server running and a database/table set up.

    3. Add reactor-core dependency if not already present, as R2DBC heavily relies on Project Reactor.

    MariaDB Connector/R2DBC supports a standard R2DBC URL format for connection:

    r2dbc:mariadb://[username[:password]@]host[:port][/database][?option=value]

    Example:

    r2dbc:mariadb://user:pass@localhost:3306/mydb?useBatchMultiSend=true

    MariaDB Connector/R2DBC also integrates seamlessly with the Spring Data R2DBC framework, providing a higher-level abstraction for reactive database access, including repositories and entity mapping.

    • MariaDB Connector/R2DBC GitHub Repository

    • R2DBC Specification

    • Spring Data R2DBC Documentation

    This page is: Copyright © 2025 MariaDB. All rights reserved.

    1. Installation

    2. Basic Usage (Native R2DBC)

    3. Connection Strings

    4. Spring Data R2DBC

    Further Resources:

    spinner
    c. Manual Installation:
    1. Download the latest stable .jar file from the MariaDB Downloads page.

    2. Add the downloaded .jar file to your project's classpath.

    Here's a simple Java example demonstrating how to establish a connection and execute a basic query using DriverManager.

    Before Running:

    1. Replace your_database_name, your_username, your_password, and your_table_name with your actual database details.

    2. Ensure you have a MariaDB server running and a database/table set up.

    MariaDB Connector/J supports various connection string formats, including options for failover and load balancing. The basic format is:

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

    For example:

    • jdbc:mariadb://localhost:3306/mydb

    • jdbc:mariadb://server1:3306,server2:3306/mydb?failover=true

    For production applications, it's highly recommended to use a connection pool to manage database connections efficiently. MariaDB Connector/J can be used with external connection pooling libraries like HikariCP or Apache Commons DBCP, or its own MariaDbPoolDataSource.

    • MariaDbDataSource: Creates a new connection each time.

    • MariaDbPoolDataSource: Maintains a pool of connections for reuse.

    When using an external pool, configure it to use org.mariadb.jdbc.Driver as the JDBC driver class.

    Quickstart Guide: MariaDB Connector/J

    1. Installation

    About MariaDB Connector/J

    2. Basic Usage (Connecting to MariaDB)

    3. Connection Strings

    4. Connection Pooling (for Production)

    spinner
    async function executeDatabaseOperations() {
        let conn;
        try {
            conn = await pool.getConnection(); // Get a connection from the pool
    
            // --- SELECT Query ---
            const rows = await conn.query("SELECT id, name FROM your_table_name WHERE status = ?", ["active"]);
            console.log("Selected Rows:", rows);
    
            // --- INSERT Query (with parameters for security) ---
            const res = await conn.query("INSERT INTO your_table_name (name, status) VALUES (?, ?)", ["New Entry", "pending"]);
            console.log("Insert Result:", res); // res will contain { affectedRows: 1, insertId: ..., warningStatus: 0 }
    
        } catch (err) {
            console.error("Database operation error:", err);
            throw err; // Re-throw to handle higher up
        } finally {
            if (conn) {
                conn.release(); // Release connection back to the pool
                console.log("Connection released to pool.");
            }
        }
    }
    
    // Call the async function
    executeDatabaseOperations()
        .then(() => console.log("All database operations attempted."))
        .catch((err) => console.error("Overall operation failed:", err))
        .finally(() => {
            // Optional: End the pool when your application is shutting down
            // pool.end();
            // console.log("Connection pool ended.");
        });
    const mariadb = require('mariadb/callback');
    
    // Create a single connection
    mariadb.createConnection({
        host: 'localhost',
        port: 3306,
        user: 'your_username',
        password: 'your_password',
        database: 'your_database_name'
    }, (err, conn) => {
        if (err) {
            console.error("Connection error:", err);
            return;
        }
    
        console.log("Connected using Callback API.");
    
        // Execute a query
        conn.query("SELECT 1 AS val", (queryErr, rows) => {
            if (queryErr) {
                console.error("Query error:", queryErr);
                conn.end(); // Close connection on error
                return;
            }
            console.log("Query Result (Callback):", rows);
    
            // Close the connection when done
            conn.end((endErr) => {
                if (endErr) {
                    console.error("Error closing connection:", endErr);
                } else {
                    console.log("Connection closed (Callback).");
                }
            });
        });
    });
    Install-Package MySqlConnector -Version 2.4.0 # Use the latest stable version
    <PackageReference Include="MySqlConnector" Version="2.4.0" /> ```
    
    **c. Using .NET CLI:**
    
    ```bash
    dotnet add package MySqlConnector --version 2.4.0 # Use the latest stable version
    string connectionString = "Server=localhost;Port=3306;Database=your_database_name;Uid=your_username;Pwd=your_password;";
    using MySqlConnector;
    using System;
    using System.Data;
    using System.Threading.Tasks;
    
    public class MariaDBConnectorNetQuickstart
    {
        private static string connectionString = "Server=localhost;Port=3306;Database=your_database_name;Uid=your_username;Pwd=your_password;";
    
        public static async Task Main(string[] args)
        {
            Console.WriteLine("Connecting to MariaDB...");
    
            try
            {
                await using var connection = new MySqlConnection(connectionString);
                await connection.OpenAsync();
                Console.WriteLine("Connection successful!");
    
                // Call your data operations here
                await SelectData(connection);
                await InsertData(connection);
    
                Console.WriteLine("Operations completed.");
            }
            catch (MySqlException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    
        // ... (Data operation methods will go here)
    }
        private static async Task SelectData(MySqlConnection connection)
        {
            string query = "SELECT id, name FROM your_table_name;";
            await using var command = new MySqlCommand(query, connection);
    
            Console.WriteLine("\nRetrieving data:");
            await using var reader = await command.ExecuteReaderAsync();
            while (await reader.ReadAsync())
            {
                int id = reader.GetInt32("id");
                string name = reader.GetString("name");
                Console.WriteLine($"ID: {id}, Name: {name}");
            }
        }
        private static async Task InsertData(MySqlConnection connection)
        {
            string query = "INSERT INTO your_table_name (name, status) VALUES (@name, @status);";
            await using var command = new MySqlCommand(query, connection);
    
            command.Parameters.AddWithValue("@name", "New Item");
            command.Parameters.AddWithValue("@status", "active");
    
            int rowsAffected = await command.ExecuteNonQueryAsync();
            Console.WriteLine($"\nRows inserted: {rowsAffected}");
        }
    sudo apt update
    sudo apt install libmariadb-dev # Or libmysqlclient-dev
    # If using Bundler (e.g., in a Rails project's Gemfile)
    # Gemfile
    # gem 'mysql2'
    bundle install
    
    # Or directly
    gem install mysql2
    require 'mysql2'
    
    begin
      client = Mysql2::Client.new(
        host: 'localhost',
        port: 3306,
        username: 'your_username',
        password: 'your_password',
        database: 'your_database_name'
      )
      puts "Successfully connected to MariaDB!"
    
      # ... database operations ...
    
    rescue Mysql2::Error => e
      puts "Error connecting to database: #{e.message}"
    ensure
      client&.close # Ensure the connection is closed
    end
    # Assuming 'client' is an open connection
    results = client.query("SELECT id, name FROM your_table_name WHERE status = 'active'")
    
    puts "\nSelected Rows:"
    results.each do |row|
      puts "ID: #{row['id']}, Name: #{row['name']}"
    end
    # INSERT Example (using prepared statement)
    statement = client.prepare("INSERT INTO your_table_name (name, status) VALUES (?, ?)")
    insert_result = statement.execute("New Item", "pending")
    puts "\nRows inserted: #{insert_result.affected_rows}, Last ID: #{insert_result.last_id}"
    
    # UPDATE Example
    update_result = client.query("UPDATE your_table_name SET status = 'completed' WHERE name = 'New Item'")
    puts "Rows updated: #{update_result.affected_rows}"
    
    # DELETE Example
    delete_result = client.query("DELETE FROM your_table_name WHERE name = 'New Item'")
    puts "Rows deleted: #{delete_result.affected_rows}"
    # Assuming 'client' is an open connection
    statement = client.prepare("SELECT * FROM users WHERE login_count = ?")
    
    # Execute with different parameters
    result1 = statement.execute(1)
    puts "\nUsers with login_count = 1:"
    result1.each { |row| puts row.inspect }
    
    result2 = statement.execute(5)
    puts "\nUsers with login_count = 5:"
    result2.each { |row| puts row.inspect }
    uint8_t reconnect;
    
    rc = mysql_get_optionv(mysql, MYSQL_OPT_RECONNECT, &reconnect);
    uint32_t timeout;
    
    rc = mysql_get_optionv(mysql, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);
    char *plugin_dir;
    
    rc = mysql_get_optionv(mysql, MYSQL_PLUGIN_DIR, &plugin_dir);
    char **commands;
    int elements;
    
    rc = mysql_get_optionv(mysql, MYSQL_INIT_COMMAND, &commands, &elements);
    /* get number of connection attributes */
    int i, elements= 0;
    char **key, **value;
    
    mysql_get_optionv(mysql, MYSQL_CONNECT_ATTRS, NULL, NULL, (void *)&elements);
    key= (char **)malloc(sizeof(char *) * elements);
    val= (char **)malloc(sizeof(char *) * elements);
    mysql_get_optionv(mysql, MYSQL_OPT_CONNECT_ATTRS, &key, &val, &elements);
    for (i=0; i < elements; i++)
      printf("key: %s value: %s", key[i], val[i]);
    const char *ssh_user;
    mysql_get_optionv(mysql, MARIADB_OPT_USERDATA, "ssh_user", (void *)ssh_user);
    /* get server port for current connection */
    unsigned int port;
    mariadb_get_infov(mysql, MARIADB_CONNECTION_PORT, void *)&port);
    /* get user name for current connection */
    const char *user;
    mariadb_get_infov(mysql, MARIADB_CONNECTION_USER, (void *)&user);
    <dependency>
        <groupId>org.mariadb</groupId>
        <artifactId>r2dbc-mariadb</artifactId>
        <version>1.4.1</version> </dependency>
    // Gradle
    implementation 'org.mariadb:r2dbc-mariadb:1.4.1' // Use the latest stable version
    <dependency>
        <groupId>org.mariadb</groupId>
        <artifactId>r2dbc-mariadb-0.9.1-spec</artifactId>
        <version>1.4.1</version> </dependency>
    // Gradle
    implementation 'org.mariadb:r2dbc-mariadb-0.9.1-spec:1.4.1' // Use the latest stable version
    import io.r2dbc.spi.ConnectionFactories;
    import io.r2dbc.spi.ConnectionFactory;
    import io.r2dbc.spi.ConnectionFactoryOptions;
    import io.r2dbc.spi.Connection;
    import io.r2dbc.spi.Result;
    import reactor.core.publisher.Flux;
    import reactor.core.publisher.Mono;
    
    import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
    import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
    import static io.r2dbc.spi.ConnectionFactoryOptions.HOST;
    import static io.r2dbc.spi.ConnectionFactoryOptions.PASSWORD;
    import static io.r2dbc.spi.ConnectionFactoryOptions.PORT;
    import static io.r2dbc.spi.ConnectionFactoryOptions.USER;
    import org.mariadb.r2dbc.MariadbConnectionConfiguration;
    import org.mariadb.r2dbc.MariadbConnectionFactory;
    
    public class MariaDBR2DBCQuickstart {
    
        public static void main(String[] args) {
            // Option 1: Using ConnectionFactoryOptions Builder (Recommended for explicit configuration)
            MariadbConnectionConfiguration conf = MariadbConnectionConfiguration.builder()
                    .host("localhost")
                    .port(3306)
                    .username("your_username")
                    .password("your_password")
                    .database("your_database_name")
                    .build();
            ConnectionFactory factory = new MariadbConnectionFactory(conf);
    
            // Option 2: Using a R2DBC Connection URL
            // ConnectionFactory factory = ConnectionFactories.get("r2dbc:mariadb://your_username:your_password@localhost:3306/your_database_name");
    
            Mono<Connection> connectionMono = Mono.from(factory.create());
    
            // --- Example: Select Data ---
            connectionMono
                .flatMapMany(connection ->
                    Flux.from(connection.createStatement("SELECT id, name FROM your_table_name WHERE status = ?")
                                       .bind(0, "active") // Bind parameter by index
                                       .execute())
                        .flatMap(result -> result.map((row, rowMetadata) -> {
                            int id = row.get("id", Integer.class);
                            String name = row.get("name", String.class);
                            return "ID: " + id + ", Name: " + name;
                        }))
                        .doFinally(signalType -> Mono.from(connection.close()).subscribe()) // Close connection when done
                )
                .doOnNext(System.out::println) // Print each row
                .doOnError(Throwable::printStackTrace) // Handle errors
                .blockLast(); // Block to ensure the main thread waits for completion (for quickstart example)
    
    
            // --- Example: Insert Data ---
            connectionMono
                .flatMap(connection ->
                    Mono.from(connection.createStatement("INSERT INTO your_table_name (name, status) VALUES (?, ?)")
                                       .bind(0, "New Item")
                                       .bind(1, "pending")
                                       .execute())
                        .flatMap(Result::getRowsUpdated) // Get number of affected rows
                        .doFinally(signalType -> Mono.from(connection.close()).subscribe()) // Close connection
                )
                .doOnNext(rowsUpdated -> System.out.println("Rows inserted: " + rowsUpdated))
                .doOnError(Throwable::printStackTrace)
                .block(); // Block for simplicity in quickstart
    
    
            System.out.println("MariaDB R2DBC operations completed.");
        }
    }
    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
        <version>3.3.3</version> </dependency>
    dependencies {
        implementation 'org.mariadb.jdbc:mariadb-java-client:3.3.3' // Use the latest stable version
    }
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class MariaDBQuickstart {
    
        // Database connection parameters
        static final String DB_URL = "jdbc:mariadb://localhost:3306/your_database_name";
        static final String USER = "your_username";
        static final String PASS = "your_password";
    
        public static void main(String[] args) {
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
    
            try {
                // Register JDBC driver (optional for modern JDBC, but good practice)
                // Class.forName("org.mariadb.jdbc.Driver");
    
                System.out.println("Connecting to database...");
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
    
                System.out.println("Creating statement...");
                stmt = conn.createStatement();
                String sql = "SELECT id, name FROM your_table_name";
                rs = stmt.executeQuery(sql);
    
                // Extract data from result set
                while (rs.next()) {
                    // Retrieve by column name
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
    
                    // Display values
                    System.out.print("ID: " + id);
                    System.out.println(", Name: " + name);
                }
            } catch (SQLException se) {
                // Handle errors for JDBC
                se.printStackTrace();
            } finally {
                // Close resources in finally block
                try {
                    if (rs != null) rs.close();
                } catch (SQLException se2) {
                    // Do nothing
                }
                try {
                    if (stmt != null) stmt.close();
                } catch (SQLException se2) {
                    // Do nothing
                }
                try {
                    if (conn != null) conn.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
                System.out.println("Database resources closed.");
            }
        }
    }
    For 32-bit systems, search for "ODBC Data Sources (32-bit)".
  • Go to the "User DSN" or "System DSN" tab (System DSN is generally preferred for broader application access).

  • Click "Add...".

  • Select "MariaDB ODBC Driver" (or "MariaDB ODBC 3.1 Driver" depending on the version) from the list and click "Finish".

  • A configuration dialog will appear. Fill in the details:

    • Data Source Name: A descriptive name for your DSN (e.g., MyMariaDBDSN).

    • TCP/IP Server: localhost or the IP address/hostname of your MariaDB server.

    • Port: 3306 (default MariaDB port).

    • User: Your database username.

    • Password: Your database password.

    • Database: The specific database you want to connect to.

  • Click "Test" to verify the connection. Click "OK" to save the DSN.

  • Debian/Ubuntu: sudo dpkg -i mariadb-connector-odbc_X.Y.Z.deb
  • Red Hat/CentOS: sudo rpm -i mariadb-connector-odbc-X.Y.Z.rpm

  • macOS: Run the .pkg installer.

  • Configure odbcinst.ini and odbc.ini:

    • The installer usually places the driver definition in /etc/odbcinst.ini (or a similar location).

    • You need to create or modify ~/.odbc.ini (for user DSNs) or /etc/odbc.ini (for system DSNs) to define your data source.

    Example odbcinst.ini (Driver Definition - usually installed automatically):

    Example odbc.ini (DSN Definition):

  • Test DSN (Optional): You can use isql (from unixodbc-dev or unixodbc package) to test your DSN:

    isql MyMariaDBDSN your_username your_password
  • Driver={MariaDB ODBC Driver};Server=localhost;Port=3306;Database=your_database_name;Uid=your_username;Pwd=your_password;

    3. Basic Usage (Connecting from Applications)

    Further Resources:

    MariaDB Connector/ODBC Downloads page
    MariaDB Connector/ODBC Downloads page
    MariaDB Connector/ODBC Documentation
    MariaDB Connector/ODBC Downloads

    F

    Identify the source file name for each line of debug or trace output.

    i

    Identify the process with the pid for each line of debug or trace output.

    g

    Enable profiling. Create a file called 'dbugmon.out' containing information that can be used to profile the program. May be followed by a list of keywords that select profiling only for the functions in that list. A null list implies that all functions are considered.

    L

    Identify the source file line number for each line of debug or trace output.

    n

    Print the current function nesting depth for each line of debug or trace output.

    N

    Number each line of dbug output.

    o

    Redirect the debugger output stream to the specified file. The default output is stderr.

    O

    As o but the file is really flushed between each write. When needed the file is closed and reopened between each write.

    a

    Like o, but opens for append.

    A

    Like O, but opens for append.

    p

    Limit debugger actions to specified processes. A process must be identified with the DBUG_PROCESS macro and match one in the list for debugger actions to occur.

    P

    Print the current process name for each line of debug or trace output.

    r

    When pushing a new state, do not inherit the previous state's function nesting level. Useful when the output is to start at the left margin.

    S

    Do function _sanity(file,line) at each debugged function until _sanity() returns something that differs from 0. (Mostly used with safemalloc)

    t

    Enable function call/exit trace lines. May be followed by a list (containing only one modifier) giving a numeric maximum trace level, beyond which no output will occur for either debugging or tracing macros. The default is a compile time option.

    field_1:field_2:field_n
    flag[,modifier,modifier,...,modifier]

    d

    Enable output from DBUG_ macros for the current state. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword. A null list of keywords implies output for all macros.

    D

    Delay after each debugger output line. The argument is the number of tenths of seconds to delay, subject to machine capabilities. I.E. -#D,20 is delay two seconds.

    f

    Limit debugging and/or tracing, and profiling to the list of named functions. Note that a null list will disable all functions. The appropriate "d" or "t" flags must still be given, this flag only limits their actions if they are enabled.

    Instead of using the mysql_debug() function you also can set the environment variable MYSQL_DEBUG\

    Enabling generation of debug information slows down the overall performance and generates huge files. In case you need debug information only for special places you can disable the generation of debug information by using mysql_debug_end().

    This function is deprecated and not supported anymore.

    See Also

    mysql_dump_debug_info()
    spinner
    file needs to be removed first. In several cases, e.g. when cross compiling
    CMakeFiles
    subfolders need to be removed too.

    If you want to use a different generator, e.g. for nmake on Windows, you need to specify the generator with the -G option. cmake --help lists the available generators for the used platform.

    CMAKE_BUILD_TYPE

    Build type: Release, RelWithDebInfo or Debug

    CMAKE_INSTALL_PREFIX

    Installation base directory

    CMAKE_C_FLAGS

    Flags for C-Compiler

    Option

    Default

    Description

    WITH_SSL

    SCHANNEL (windows), otherwise OPENSSL

    Specifies type of TLS/SSL library. Valid values are OPENSSL, GNUTLS, and SCHANNEL (Windows only).

    Client plugins can be configured as dynamic plugins (DYNAMIC) or built-in plugins (STATIC) by specifying the plugin name followed by suffix _PLUGIN_TYPE as key, and "DYNAMIC" or "STATIC" as value.

    E.g. for building dialog plugin as a built-in plugin, for versions < Connector/C 3.0.4

    Beginning with C/C 3.0.4

    Connector/C 3.0 supports the following plugins:

    Plugin

    Type

    Default

    Description

    PVIO_SOCKET

    IO

    static

    plugin for client server communication via socket

    cmake ../connector_c -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local

    Configuration settings

    Reconfiguration

    cmake .. -D{PLUGIN_NAME}_PLUGIN_TYPE=[STATIC|DYNAMIC|OFF]
    cmake .. -DCLIENT_PLUGIN_{PLUGIN_NAME}=[STATIC|DYNAMIC|OFF]

    Generator options

    CMake-related configuration settings

    TLS/SSL options

    Client plugins

    spinner

    MARIADB_RPL_SERVER_ID

    uint32_t

    The server ID to use when registering this client as a replica.

    MARIADB_RPL_FLAGS

    uint32_t

    Bitmask of protocol flags. See Replication API Types and Definitions for valid flag values.

    MARIADB_RPL_VERIFY_CHECKSUM

    uint32_t

    CRC32 checksum verification for received events. Added in Connector/C 3.3.5.

    MARIADB_RPL_PORT

    uint32_t

    Port number to report when registering this client as a replica. Added in Connector/C 3.3.5.

    MARIADB_RPL_HOST

    char *

    Host name to report when registering this client as a replica. Added in Connector/C 3.3.5.

    MARIADB_RPL_SEMI_SYNC

    uint_32_t

    Enable or disable semi-synchronous replication. Added in Connector/C 3.3.6.

    sudo yum install MariaDB-shared
    sudo yum install MariaDB-devel
    sudo apt-get install libmariadb3
    sudo apt-get install libmariadb-dev
    sudo zypper install MariaDB-shared
    sudo zypper install MariaDB-devel

    Install with a Package Manager (Recommended for Linux)

    Install on Windows

    Install from Source

    API Reference

    Configuration with Option Files

    Known Issues

    Need Help or Want to Contribute?

    License

    Building Connector/C From Source
    MariaDB Client Library for C API Functions
    MariaDB Client Library for C API Prepared Statement Functions
    Configuring MariaDB Connector/C with Option Files
    CONC project on MariaDB's Jira bug tracker
    mariadb-connector-c repository
    spinner

    Replication API Types and Definitions

    All enumerations and preprocessor definitions for the Binglog/Replication API are defined in include/mariadb_rpl.h.

    The following API types and definitions are used by the Binlog/Replication API:

    Type or Definition
    Description

    Install MariaDB Connector/C

    Complete MariaDB installation guide. Complete setup instructions for Linux, Windows, and macOS with configuration and verification for production use.

    MariaDB Connector/C supports several Linux distributions and Microsoft Windows.

    To install MariaDB Connector/C on Linux using APT, YUM, or ZYpp, you must configure your system to use either the ES Package Repository or the CS Package Repository.

    If your system is already configured to use one of these package repositories, you can skip to .

    Choose a package repository to configure:

    PVIO_SHMEM

    IO

    dynamic

    plugin for client server communication via shared memory

    PVIO_NPIPE

    IO

    static

    plugin for client server communication via named pipe

    DIALOG

    Authentication

    dynamic

    Authentication for user input, e.g. for PAM authentication

    MYSQL_OLD_PASSWORD

    Authentication

    static

    Pre. 4.1 authentication (deprecated). Disabled by default in current versions; not built unless explicitly enabled.

    MYSQL_NATIVE_PASSWORD

    Authentication

    static

    Default authentication

    MYSQL_CLEAR_PASSWORD

    Authentication

    dynamic

    Sends password without hashing or encryption

    AUTH_GSSAPI_CLIENT

    Authentication

    dynamic

    Kerberos/GSSAPI authentication plugin

    SHA256_PASSWORD

    Authentication

    dynamic

    SHA256 password authentication plugin

    REPLICATION

    Connection

    OFF

    Replication/fail over plugin (experimental)

    [MariaDB ODBC Driver]
    Description = MariaDB Connector/ODBC
    Driver = /usr/lib/x86_64-linux-gnu/odbc/libmaodbc.so # Adjust path for your system
    Setup = /usr/lib/x86_64-linux-gnu/odbc/libmaodbc.so # Adjust path for your system
    UsageCount = 1
    FileUsage = 1
    CPTimeout =
    CPReconnect =
    [MyMariaDBDSN]
    Description = My MariaDB Database
    Driver = MariaDB ODBC Driver # Matches the name from odbcinst.ini
    SERVER = localhost
    PORT = 3306
    DATABASE = your_database_name
    UID = your_username
    PASSWORD = your_password
    OPTION =

    mariadb_row_event_type

    Row operation type for write, update, and delete row events.

    Flags

    Bitmask constants for controlling binary log dump behaviour. Passed via the MARIADB_RPL_FLAGS option.

    mariadb_rpl_option is the enumeration of options accepted by mariadb_rpl_optionsv() and mariadb_rpl_get_optionsv(). Options are used to configure a MARIADB_RPL handle before opening a binary log stream.

    Option descriptions

    • MARIADB_RPL_FILENAME → Name of the binary log file to open, and its length in bytes.

    • MARIADB_RPL_START → Binary log position from which to start reading events.

    • MARIADB_RPL_SERVER_ID → The server ID to use when registering this client as a replica.

    • MARIADB_RPL_FLAGS → Bitmask of protocol flags controlling binary log dump behavior. See Flags for valid values.

    • MARIADB_RPL_GTID_CALLBACK → Pointer to a GTID callback function, called when a GTID event is received.

    • MARIADB_RPL_GTID_DATA → User data pointer passed to the GTID callback function.

    • MARIADB_RPL_BUFFER → Pre‑allocated buffer for event data, and its size.

    mariadb_rpl_event is the enumeration of all binary log event types. The event_type field of MARIADB_RPL_EVENT is set to one of these values to indicate which event structure is active in the event union.

    mariadb_row_event_type identifies the row operation performed by a WRITE_ROWS_EVENT, UPDATE_ROWS_EVENT, or DELETE_ROWS_EVENT.

    Value
    Constant
    Description

    0

    WRITE_ROWS

    A row was inserted. The row_data field contains the new row image.

    1

    UPDATE_ROWS

    A row was updated.

    The following flags are passed as a bitmask to the MARIADB_RPL_FLAGS option via mariadb_rpl_optionsv(). Multiple flags can be combined using the bitwise OR operator (|) to control binary log dump behavior.

    • MariaDB Binlog/Replication API Reference

    • Binlog/API Data Structures

    • Replication API Function Reference

    mariadb_rpl_option

    Options for configuring a MARIADB_RPL replication handle. Used by mariadb_rpl_optionsv() and mariadb_rpl_get_optionsv()

    mariadb_rpl_event

    Event type identifiers returned in the event_type field of MARIADB_RPL_EVENT.

    enum mariadb_rpl_option {
      MARIADB_RPL_FILENAME,       /* Filename and length */
      MARIADB_RPL_START,          /* Start position */
      MARIADB_RPL_SERVER_ID,      /* Server ID */
      MARIADB_RPL_FLAGS,          /* Protocol flags */
      MARIADB_RPL_GTID_CALLBACK,  /* GTID callback function */
      MARIADB_RPL_GTID_DATA,      /* GTID data */
      MARIADB_RPL_BUFFER,
      MARIADB_RPL_VERIFY_CHECKSUM,
      MARIADB_RPL_UNCOMPRESS,
      MARIADB_RPL_HOST,
      MARIADB_RPL_PORT,
      MARIADB_RPL_EXTRACT_VALUES,
      MARIADB_RPL_SEMI_SYNC,
    };
    enum mariadb_rpl_event {
      UNKNOWN_EVENT= 0,
      START_EVENT_V3= 1,
      QUERY_EVENT= 2,
      STOP_EVENT= 3,
      ROTATE_EVENT= 4,
      INTVAR_EVENT= 5,
      LOAD_EVENT= 6,
      SLAVE_EVENT= 7,
      CREATE_FILE_EVENT= 8,
      APPEND_BLOCK_EVENT= 9,
      EXEC_LOAD_EVENT= 10,
      DELETE_FILE_EVENT= 11,
      NEW_LOAD_EVENT= 12,
      RAND_EVENT= 13,
      USER_VAR_EVENT= 14,
      FORMAT_DESCRIPTION_EVENT= 15,
      XID_EVENT= 16,
      BEGIN_LOAD_QUERY_EVENT= 17,
      EXECUTE_LOAD_QUERY_EVENT= 18,
      TABLE_MAP_EVENT = 19,
    
      PRE_GA_WRITE_ROWS_EVENT = 20, /* deprecated */
      PRE_GA_UPDATE_ROWS_EVENT = 21, /* deprecated */
      PRE_GA_DELETE_ROWS_EVENT = 22, /* deprecated */
    
      WRITE_ROWS_EVENT_V1 = 23,
      UPDATE_ROWS_EVENT_V1 = 24,
      DELETE_ROWS_EVENT_V1 = 25,
      INCIDENT_EVENT= 26,
      HEARTBEAT_LOG_EVENT= 27,
      IGNORABLE_LOG_EVENT= 28,
      ROWS_QUERY_LOG_EVENT= 29,
      WRITE_ROWS_EVENT = 30,
      UPDATE_ROWS_EVENT = 31,
      DELETE_ROWS_EVENT = 32,
      GTID_LOG_EVENT= 33,
      ANONYMOUS_GTID_LOG_EVENT= 34,
      PREVIOUS_GTIDS_LOG_EVENT= 35,
      TRANSACTION_CONTEXT_EVENT= 36,
      VIEW_CHANGE_EVENT= 37,
      XA_PREPARE_LOG_EVENT= 38,
      PARTIAL_UPDATE_ROWS_EVENT = 39,
    
      /*
        Add new events here - right above this comment!
        Existing events (except ENUM_END_EVENT) should never change their numbers
      */
    
      /* New MySQL/Sun events are to be added right above this comment */
      MYSQL_EVENTS_END,
    
      MARIA_EVENTS_BEGIN= 160,
      ANNOTATE_ROWS_EVENT= 160,
      BINLOG_CHECKPOINT_EVENT= 161,
      GTID_EVENT= 162,
      GTID_LIST_EVENT= 163,
      START_ENCRYPTION_EVENT= 164,
      QUERY_COMPRESSED_EVENT = 165,
      WRITE_ROWS_COMPRESSED_EVENT_V1 = 166,
      UPDATE_ROWS_COMPRESSED_EVENT_V1 = 167,
      DELETE_ROWS_COMPRESSED_EVENT_V1 = 168,
      WRITE_ROWS_COMPRESSED_EVENT = 169,
      UPDATE_ROWS_COMPRESSED_EVENT = 170,
      DELETE_ROWS_COMPRESSED_EVENT = 171,
    
      /* Add new MariaDB events here - right above this comment!  */
    
      ENUM_END_EVENT /* end marker */
    };
    enum mariadb_row_event_type {
      WRITE_ROWS= 0,
      UPDATE_ROWS= 1,
      DELETE_ROWS= 2
    };
    #define MARIADB_RPL_BINLOG_DUMP_NON_BLOCK 1
    #define MARIADB_RPL_BINLOG_SEND_ANNOTATE_ROWS 2
    #define MARIADB_RPL_IGNORE_HEARTBEAT (1 << 17)

    mariadb_rpl_option

    mariadb_rpl_event

    mariadb_row_event_type

    Flags

    See Also

    • MariaDB Enterprise Server package repository

    • Available to customers of MariaDB Corporation

    • Available for APT, YUM, and ZYpp on supported Linux distributions

    • MariaDB Community Server package repository

    • Publicly available

    • Available for APT, YUM, and ZYpp on supported Linux distributions

    MariaDB Connector/C is available from the same package repository as MariaDB Enterprise Server.

    To configure the ES package repository:

    1. Install curl.

      Install via APT on Debian, Ubuntu:

      sudo apt install curl

      Install via YUM on CentOS, RHEL, Rocky Linux:

      sudo yum install curl

      Install via ZYpp on SLES:

      sudo zypper install curl
    2. Download the utility, validate its checksum, and ensure that its permissions allow it to be executed:

      $ curl -LsSO https://dlm.mariadb.com/enterprise-release-helpers/mariadb_es_repo_setup
      $ echo "${checksum}  mariadb_es_repo_setup" \
          | sha256sum -c -
      $ chmod +x mariadb_es_repo_setup
      1. Checksums of the various releases of the mariadb_es_repo_setup script can be found in the section at the bottom of the page. Substitute ${checksum} in the example above with the latest checksum.

    3. Retrieve your Customer Download Token at and substitute your token for CUSTOMER_DOWNLOAD_TOKEN in the following step.

    4. Configure the ES package repository using the utility:

      • All major releases of ES contain the same version of MariaDB Connector/C.

      • By default, the utility will configure your system to use the package repository for ES 10.6.

    5. using the package repository.

    MariaDB Connector/C is available from the same package repository as MariaDB Community Server.

    To configure the CS package repository:

    1. Install curl.

      Install via APT on Debian, Ubuntu:

      $ sudo apt install curl

      Install via YUM on CentOS, RHEL, Rocky Linux:

      $ sudo yum install curl

      Install via ZYpp on SLES:

      $ sudo zypper install curl
    2. Download the utility, validate its checksum, and ensure that its permissions allow it to be executed:

      curl -LsSO https://r.mariadb.com/downloads/mariadb_repo_setup
      echo "${checksum} mariadb_repo_setup" \
          | sha256sum -c -
      chmod +x mariadb_repo_setup
      1. Checksums of the various releases of the mariadb_repo_setup script can be found in the section at the bottom of the page. Substitute ${checksum} in the example above with the latest checksum.

    3. Configure the CS package repository using the utility:

      • All major releases of CS contain the same version of MariaDB Connector/C.

      • By default, the utility will configure your system to use the package repository for CS 10.6.

    4. using the package repository.

    On supported Linux distributions, MariaDB Connector/C can be installed using APT, YUM, or ZYpp if the system is configured to use the ES Package Repository or the CS Package Repository.

    To install MariaDB Connector/C on CentOS, RHEL, and Rocky Linux, you can use YUM if you have the ES Package Repository or CS Package Repository configured.

    Install MariaDB Connector/C and package dependencies:

    To install MariaDB Connector/C on Debian and Ubuntu, you can use APT if you have the ES Package Repository or CS Package Repository configured.

    Install MariaDB Connector/C and package dependencies:

    To install MariaDB Connector/C on SLES, you can use ZYpp if you have the ES Package Repository or CS Package Repository configured.

    Install MariaDB Connector/C and package dependencies:

    MariaDB Connector/C can be installed on supported Linux distributions via a binary tarball package:

    1. Go to the MariaDB Connector/C download page

    2. Ensure the "Product" dropdown reads "C connector."

    3. In the "Version" dropdown, select the version you want to download.

    4. In the "OS" dropdown, select your Linux distribution.

    5. Click on the "Download" button to download the binary tarball package.

    MariaDB Connector/C can be installed on Microsoft Windows via an MSI package:

    1. Go to the MariaDB Connector/C download page

    2. Ensure the "Product" dropdown reads "C connector."

    3. In the "Version" dropdown, select the version you want to download.

    4. 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.

    5. Click on the "Download" button to download the MSI package.

    6. When the MSI package finishes downloading, run it and follow the on-screen instructions.

    This page is: Copyright © 2025 MariaDB. All rights reserved.

    Package Repository

    Configure Package Repository (Linux)

    install MariaDB Connector/C

    Description

    sudo yum install MariaDB-shared MariaDB-devel
    sudo apt install libmariadb3 libmariadb-dev
    sudo zypper install MariaDB-shared MariaDB-devel

    ES Package Repository

    CS Package Repository

    Installation

    Installation via Package Repository (Linux)

    Install on CentOS, RHEL, Rocky Linux

    Install on Debian, Ubuntu

    Install on SLES

    Install via Binary Tarball (Linux)

    Install via MSI (Windows)

    spinner

    MariaDB Connector/C Overview

    Complete Connector/C reference: Windows MSI install, Linux packages (yum/apt/zypper), MariaDB-shared/devel libraries, and option file configuration.

    Browse & download the latest MariaDB connectors

    The most recent release of is:

    MariaDB Connector/C is used to connect applications developed in C/C++ to MariaDB and MySQL databases.The client library is LGPL licensed.

    Supported Versions

    Server Compatibility

    MariaDB Connector/C is compatible with all MariaDB and MySQL server versions.

    Supported Release Series

    The following MariaDB Connector/C release series are currently supported:

    Release Series
    Stable (GA) Date

    For End of Standard Support and End of Life dates, see the .

    Most users install MariaDB Connector/C from the packages distributed with MariaDB Server, which use the server's versioning scheme rather than the connector's. To find the installed Connector/C version, use the mariadb_config utility with the --cc_version option:

    An application can also retrieve the client library version at runtime by calling (string) or (numeric).

    MariaDB Connector/C is distributed with MariaDB Server packages. Eventually, it will completely replace the functionality that has traditionally been performed by libmysqlclient in those packages. Currently, MariaDB Connector/C has replaced libmysqlclient as the client library for client utilities that are distributed with MariaDB Server. See for more information.

    MariaDB Connector/C packages can be downloaded by selecting your desired version from the following page:

    • MariaDB Connector/C packages can also be downloaded by selecting C/C++ connector as the Product on the following page:

    See the instructions below for information on how to install the MariaDB Connector/C package for your operating system.

    To install MariaDB Connector/C on Windows, we distribute . The MSI installation process is fairly straightforward. Both 32-bit and 64-bit MSI packages are available.

    MariaDB Connector/C is distributed in on Linux.

    Since MariaDB Connector/C is now integrated with MariaDB Server, it can also be installed via a package manager on Linux. In order to do so, your system needs to be configured to install from one of the MariaDB repositories. The repository needs to be configured for or later.

    You can configure your package manager to install it from MariaDB Corporation's MariaDB Package Repository by using the .

    You can also configure your package manager to install it from MariaDB Foundation's MariaDB Repository by using the .

    Installing with yum/dnf

    On RHEL, CentOS, Fedora, and other similar Linux distributions, it is highly recommended to install the relevant from MariaDB's repository using or . Starting with RHEL 8 and Fedora 22, yum has been replaced by dnf, which is the next major version of yum. However, yum commands still work on many systems that use dnf. For example:

    If you want to build applications with MariaDB Connector/C, then you will also need to install the development package. For example:

    Installing with apt-get

    On Debian, Ubuntu, and other similar Linux distributions, it is highly recommended to install the relevant from MariaDB's repository using . For example:

    If you want to build applications with MariaDB Connector/C, then you will also need to install the development package. For example:

    Installing with zypper

    On SLES, OpenSUSE, and other similar Linux distributions, it is highly recommended to install the relevant from MariaDB's repository using .

    For example:

    If you want to build applications with MariaDB Connector/C, then you will also need to install the development package. For example:

    See for information on how to build MariaDB Connector/C from source.

    MariaDB Connector/C has exactly the same API as the MySQL Connector/C for MySQL 5.5

    The function reference is available at:

    It is also downloadable in html format from mariadb-client-doc.zip

    Just like MariaDB Server and libmysqlclient, MariaDB Connector/C can also read configuration options from client in .

    See for more information.

    • double to string conversion for prepared statements doesn't work correctly

    • Connector 3.0.7 and below doesn't support the MySQL 8.0 default authentication protocol, . This protocol should be supported in Connector/C 3.0.8 and above.

    If you find a bug, please report it via the on .

    The source code is available at the on GitHub.

    GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

    For licensing questions, see the .

    2

    DELETE_ROWS

    A row was deleted. The row_data field contains the deleted row image.

    To configure your system to use the ES package repository for a specific major release, use the option.
    To configure your system to use the CS package repository for a specific major release, use the option.
    Configured with the utility
    Configured with the utility
    sudo ./mariadb_es_repo_setup --token="CUSTOMER_DOWNLOAD_TOKEN" --apply \
       --mariadb-server-version="10.6"
    sudo ./mariadb_repo_setup \
       --mariadb-server-version="mariadb-10.6"
    Customer Download Token at the MariaDB Customer Portal
    mariadb_es_repo_setup
    Install MariaDB Connector/C
    mariadb_repo_setup
    Install MariaDB Connector/C
    ES Package Repository
    CS Package Repository

    3.4

    February 2025

    3.3

    July 2022

    mariadb_config --cc_version
    3.4.10
    sudo yum install MariaDB-shared
    sudo yum install MariaDB-devel
    sudo apt-get install libmariadb3
    sudo apt-get install libmariadb-dev
    sudo zypper install MariaDB-shared
    sudo zypper install MariaDB-devel

    Checking Your Installed Version

    The mariadb_config --version option returns the MariaDB Server package version, not the Connector/C version. Use --cc_version for the Connector/C version.

    Integration with MariaDB Server

    Installing MariaDB Connector/C

    Installing MariaDB Connector/C on Windows

    Installing MariaDB Connector/C on Linux

    Installing with a Package Manager

    Installing MariaDB Connector/C from Source

    API - Function Reference

    Configuring MariaDB Connector/C with Option Files

    Known Bugs and Limitations

    Reporting Bugs

    Source Code

    License

    MariaDB Engineering Policy
    mysql_get_client_info()
    mysql_get_client_version()
    MDEV-9055
    #connectors
    MariaDB Repository Configuration Tool
    apt-get
    Building Connector/C From Source
    MariaDB Client Library for C API Functions
    MariaDB Client Library for C API Prepared Statement Functions
    Configuring MariaDB Connector/C with Option Files
    caching_sha2_password
    CONC project
    MariaDB's Jira bug tracker
    mariadb-connector-c repository
    Download Connectors
    MariaDB Connector/C
    Download Connector/C 3.4.9

    Connector/Python Guide

    Quickstart guide for MariaDB Connector/Python

    Quickstart Guide: MariaDB Connector/Python

    MariaDB Connector/Python is the official Python client library for connecting applications to MariaDB and MySQL databases. It implements the Python DB API 2.0 (PEP-249) standard, ensuring compatibility with common Python database programming patterns.

    Version 2.0 offers flexible distribution options:

    • Pure Python - Works everywhere, no compiler or dependencies required

    • C extension - Maximum performance (2-12× faster on data-heavy workloads)

    • Pre-compiled wheels - No MariaDB Connector/C installation needed

    • Async/await support - Native asynchronous operations for modern Python applications

    • - Connection parameters, methods, and attributes

    • - Cursor parameters, methods, and attributes

    • - Pool configuration and usage

    Before installing MariaDB Connector/Python, ensure you have:

    • Python: Version 3.9 or later

    • MariaDB Connector/C: Version 3.3.1 or later (optional - only required for C extension from source)

    Version 1.1 (stable / GA)

    A plain pip install installs the latest stable release (1.1). It always installs the C extension and requires MariaDB Connector/C to be pre-installed; connection pooling is included by default.

    To pin to a specific 1.1 release:

    Version 2.0 (Release Candidate)

    Version 2.0 is a pre-release, so the --pre flag is required — without it, pip installs the latest GA release (1.1). Choose the option that best fits your needs:

    Here's a simple Python example demonstrating how to connect to MariaDB, execute queries, and manage transactions.

    Using Dictionary Configuration (All Versions):

    Using URI Connection String (Since Version 2.0):

    Before Running:

    1. Replace your_username, your_password, and your_database_name with your actual MariaDB server credentials.

    2. Ensure you have a MariaDB server running and the specified database exists.

    3. The example assumes your_table_name

    • Parameterized Queries: Always use parameterized queries (e.g., VALUES (?, ?)) to prevent SQL injection vulnerabilities. Parameters are passed as a tuple or list to the execute() method.

    • Transactions (conn.commit() / conn.rollback()): By default, autocommit is disabled. Call conn.commit()

    For modern async applications (FastAPI, Starlette, etc.):

    Async Connection Pool:

    • Migration Guide (1.1 to 2.0)

    • Async/Await Support

    MariaDB Connector/C Data Structures

    Reference for the public data structures in MariaDB Connector/C, including MYSQL, MYSQL_RES, MYSQL_STMT, MYSQL_FIELD, MYSQL_BIND, and MYSQL_TIME with all member definitions.

    This page describes the public data structures used by MariaDB Connector/C.

    The MYSQL structure represents one database connection and is used by most of MariaDB Connector/C's API functions. The MYSQL structure needs to be allocated and initialized by the API function. It will be released by the function.

    The MYSQL_RES structure represents a result set which contains data and metadata information. It will be returned by the , and API functions and needs to be released by .

    MYSQL_ROW represents an array of character pointers, pointing to the columns of the actual data row. Data will be received by the

    is
    users
    with columns
    id
    ,
    name
    ,
    email
    . Adjust the table/column names as needed.
    to save changes or
    conn.rollback()
    to undo them.
  • Error Handling: Use try...except mariadb.Error blocks to gracefully handle database-related exceptions.

  • Resource Management: Always close your cursor and connection objects in a finally block to ensure resources are released, even if errors occur.

  • URI Connections: Version 2.0 supports standard URI connection strings for cleaner configuration.

  • Binary Protocol: Use binary=True for prepared statements and better performance with repeated queries.

  • MariaDB Developers Python Quickstart (GitHub)

    API Reference

    1. Prerequisites

    2. Installation

    Version 1.1 is the latest stable (GA) release; version 2.0 is currently a Release Candidate (RC). Choose the version that fits your needs below. Do not use non-stable (non-GA) releases in production.

    3. Basic Usage

    Important Notes:

    4. Async/Await Support (New in 2.0)

    Further Resources:

    Connection API
    Cursor API
    Connection Pooling API
    PyPI MariaDB Connector/Python
    MariaDB Connector/Python Documentation
    pip install mariadb
    pip install mariadb==1.1.14
    # Pure Python (recommended for most users)
    pip install --pre mariadb
    
    # Pre-compiled binary wheels (best for production)
    pip install --pre mariadb[binary,pool]
    
    # C extension from source (maximum performance, requires MariaDB Connector/C)
    pip install --pre mariadb[c,pool]
    import mariadb
    import sys
    
    # 1. Database Connection Configuration
    db_config = {
        'host': 'localhost',
        'port': 3306,
        'user': 'your_username',
        'password': 'your_password',
        'database': 'your_database_name'
    }
    
    def run_db_operations():
        conn = None
        cursor = None
        try:
            # 2. Establish a Connection
            print("Connecting to MariaDB...")
            conn = mariadb.connect(**db_config)
            print("Connection successful!")
    
            # 3. Create a Cursor Object
            cursor = conn.cursor()
    
            # ... (rest of the code continues below)
    import mariadb
    import sys
    
    # 1. Database Connection URI (Available since MariaDB Connector/Python 2.0)
    DATABASE_URL = "mariadb://your_username:your_password@localhost:3306/your_database_name"
    
    def run_db_operations():
        conn = None
        cursor = None
        try:
            # 2. Establish a Connection
            print("Connecting to MariaDB...")
            conn = mariadb.connect(DATABASE_URL)
            print("Connection successful!")
    
            # 3. Create a Cursor Object
            cursor = conn.cursor()
    
            # --- Example: Create a Table (if it doesn't exist) ---
            try:
                cursor.execute("""
                    CREATE TABLE IF NOT EXISTS users (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        name VARCHAR(255) NOT NULL,
                        email VARCHAR(255) UNIQUE
                    )
                """)
                conn.commit() # Commit the transaction for DDL
                print("Table 'users' created or already exists.")
            except mariadb.Error as e:
                print(f"Error creating table: {e}")
                conn.rollback() # Rollback in case of DDL error
    
            # --- Example: Insert Data (Parameterized Query) ---
            print("\nInserting data...")
            insert_query = "INSERT INTO users (name, email) VALUES (?, ?)"
            try:
                cursor.execute(insert_query, ("Alice Wonderland", "alice@example.com"))
                cursor.execute(insert_query, ("Bob Builder", "bob@example.com"))
                conn.commit() # Commit the transaction for DML
                print(f"Inserted {cursor.rowcount} rows.")
                print(f"Last inserted ID: {cursor.lastrowid}")
            except mariadb.IntegrityError as e:
                print(f"Error inserting data (might be duplicate email): {e}")
                conn.rollback()
            except mariadb.Error as e:
                print(f"Error inserting data: {e}")
                conn.rollback()
    
            # --- Example: Select Data ---
            print("\nSelecting data...")
            select_query = "SELECT id, name, email FROM users WHERE name LIKE ?"
            cursor.execute(select_query, ("%Alice%",)) # Note the comma for single parameter tuple
            
            print("Fetched data:")
            for row in cursor:
                print(f"ID: {row[0]}, Name: {row[1]}, Email: {row[2]}")
    
            # --- Example: Update Data ---
            print("\nUpdating data...")
            update_query = "UPDATE users SET name = ? WHERE email = ?"
            cursor.execute(update_query, ("Alicia Wonderland", "alice@example.com"))
            conn.commit()
            print(f"Rows updated: {cursor.rowcount}")
    
            # --- Example: Delete Data ---
            print("\nDeleting data...")
            delete_query = "DELETE FROM users WHERE name = ?"
            cursor.execute(delete_query, ("Bob Builder",))
            conn.commit()
            print(f"Rows deleted: {cursor.rowcount}")
    
        except mariadb.Error as e:
            print(f"An error occurred: {e}")
            sys.exit(1)
        finally:
            # 4. Close Cursor and Connection
            if cursor:
                cursor.close()
                print("Cursor closed.")
            if conn:
                conn.close()
                print("Connection closed.")
    
    if __name__ == "__main__":
        run_db_operations()
    import asyncio
    import mariadb
    
    async def async_operations():
        # Connect asynchronously
        conn = await mariadb.asyncConnect(
            "mariadb://your_username:your_password@localhost/your_database_name"
        )
        
        try:
            cursor = await conn.cursor()
            
            # Execute async query
            await cursor.execute("SELECT id, name, email FROM users WHERE id = ?", (1,))
            user = await cursor.fetchone()
            print(f"User: {user}")
            
            await cursor.close()
        finally:
            await conn.close()
    
    # Run async function
    asyncio.run(async_operations())
    import asyncio
    import mariadb
    
    async def main():
        # Create async pool
        pool = await mariadb.create_async_pool(
            "mariadb://user:password@localhost/mydb",
            min_size=5,
            max_size=20
        )
        
        # Use pool
        async with await pool.acquire() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute("SELECT COUNT(*) FROM users")
                count = (await cursor.fetchone())[0]
                print(f"Total users: {count}")
        
        await pool.close()
    
    asyncio.run(main())
    function. The size of the array is the number of columns for the current row.

    The MYSQL_STMT structure represents a prepared statement handle and is used by MariaDB Connector/C's prepared statement API functions. The MYSQL_STMT structure needs to be allocated and initialized by the mysql_stmt_init() function and needs to be released by the mysql_stmt_close() function.

    The MYSQL_FIELD structure describes the metadata of a column. It can be obtained by the mysql_fetch_field() function.

    It has the following members:

    Type
    Member
    Description

    char *

    name

    The name of the column

    unsigned int

    name_length

    The length of column name

    The MYSQL_BIND structure is used to provide parameters for prepared statements or to receive output column value from prepared statements.

    Type
    Member
    Description

    unsigned long *

    length

    Pointer for the length of the buffer (not used for parameters). The length is ignored for numeric and fixed size data types, as the buffer_type value determines the size of the data.

    my_bool *

    is_null

    Pointer which indicates if column is NULL (not used for parameters)

    The MYSQL_TIME structure is used for date and time values in prepared statements. It has the following members:

    Type
    Member
    Description

    unsigned int

    year

    Year

    unsigned int

    month

    Month

    The MARIADB_X509_INFO structure contains information about the peer certificate. This information is only available for TLS/SSL connections.

    Type
    Member
    Description

    int

    version

    Peer certificate version

    char *

    issuer

    Issuer of peer certificate

    MARIADB_X509_INFO was added in MariaDB Connector/C 3.4.1

    MYSQL

    The MYSQL structure should be considered as opaque; copying or changing values of its members might produce unexpected results, errors or program crashes.

    MYSQL_RES

    The MYSQL_RES structure should be considered as opaque; copying or changing values of its members might produce unexpected results, errors or program crashes.

    MYSQL_ROW

    mysql_init()
    mysql_close()
    mysql_use_result()
    mysql_store_result()
    mysql_stmt_result_metadata()
    mysql_free_result()

    After freeing the result set with MYSQL_ROW becomes invalid.

    MYSQL_STMT

    The MYSQL_STMT structure should be considered as opaque; copying or changing values of its members might produce unexpected results, errors or program crashes.

    MYSQL_FIELD

    MYSQL_BIND

    MYSQL_TIME

    MARIADB_X509_INFO

    mysql_fetch_row()
    spinner

    MariaDB Connector/C Types and Definitions

    Reference for MariaDB Connector/C types and definitions, including enumeration constants for field types, statement options, cursor types, indicator types, field flags, and server status.

    MariaDB Connector/C provides the following types and definitions.

    Enumeration Types

    enum mysql_option

    enum mysql_option is used as a parameter in mysql_optionsv() and mysql_get_optionsv() API functions. For a list of integral constants and their meanings, please check the documentation of mysql_get_optionsv().

    enum enum_mysql_timestamp_type

    enum enum_mysql_timestamp_type is used in the MYSQL_TIME structure and indicates the type. It has the following constants:

    • MYSQL_TIMESTAMP_NONE

    • MYSQL_TIMESTAMP_ERROR

    • MYSQL_TIMESTAMP_DATE

    • MYSQL_TIMESTAMP_DATETIME

    • MYSQL_TIMESTAMP_TIME

    enum enum_mysql_set_option is used as a parameter in and has the following constants:

    • MYSQL_OPTION_MULTI_STATEMENTS_ON

    • MYSQL_OPTION_MULTI_STATEMENTS_OFF

    enum enum_field_types describes the different field types used by MariaDB and has the following constants:

    • MYSQL_TYPE_DECIMAL

    • MYSQL_TYPE_TINY

    • MYSQL_TYPE_SHORT

    enum mysql_enum_shutdown_level is used as a parameter in and has the following constants:

    • SHUTDOWN_DEFAULT

    • KILL_QUERY

    • KILL_CONNECTION

    enum_stmt_attr_type is used to set different statement options. For a detailed description please check function.

    enum_cursor_type specifies the cursor type and is used in function. Currently the following constants are supported:

    • CURSOR_TYPE_READ_ONLY

    • CURSOR_TYPE_NO_CURSOR

    enum_indicator_type describes the type of indicator used for prepared statements bulk operations.

    The following field flags are used in structure.

    The server_status can be obtained by the function using the MARIADB_CONNECTION_SERVER_STATUS option.

    char *

    org_name

    The original name of the column

    unsigned int

    org_name_length

    The length of original column name

    char *

    table

    The name of the table

    unsigned int

    table_length

    The length of table name

    char *

    org_table

    The original name of the table

    unsigned int

    org_table_length

    The length of original table name

    char *

    db

    The name of the database (schema)

    unsigned int

    db_length

    The length of database name

    char *

    catalog

    The catalog name (always 'def')

    unsigned int

    catalog_length

    The length of catalog name

    char *

    def

    default value

    unsigned int

    def_length

    The length of default value

    unsigned long

    length

    The length (width) of the column definition

    unsigned long

    max_length

    The maximum length of the column value

    unsigned int

    flags

    Flags

    unsigned int

    decimals

    Number of decimals

    enum enum_field_types

    type

    Field type

    my_bool *

    error

    Pointer which indicates if an error occurred

    void *

    buffer

    Data buffer which contains or receives data

    char *

    u.indicator

    Array of indicator variables for bulk operation parameter

    unsigned long

    buffer_length

    Length of buffer

    enum enum_field_types

    buffer_type

    Buffer type

    unsigned long

    length_value

    Used if address of length_value is assigned to MYSQL_BIND::length

    my_bool

    error_value

    Used if address of error_value is assigned to MYSQL_BIND::error

    my_bool

    is_null_value

    Used if address of is_null_value is assigned to MYSQL_BIND::is_null

    my_bool

    is_unsigned

    Set if integer type is unsigned

    unsigned int

    day

    Day

    unsigned int

    hour

    Hour

    unsigned int

    minute

    Minute

    unsigned int

    second

    Second

    unsigned long

    second_part

    Fractional seconds (max. 6 digits)

    my_bool

    neg

    Negative value

    enum enum_mysql_timestamp_type

    time_type

    Time Type

    char *

    subject

    Subject of peer certificate

    char[129]

    fingerprint

    Fingerprint (SHA256, 384 or 512)

    struct tm

    not_before

    Start date of peer certificate

    struct tm

    not_after

    Expiration date of peer certificate

    mysql_free_result()

    MYSQL_TYPE_LONG

  • MYSQL_TYPE_FLOAT

  • MYSQL_TYPE_DOUBLE

  • MYSQL_TYPE_NULL

  • MYSQL_TYPE_TIMESTAMP

  • MYSQL_TYPE_LONGLONG

  • MYSQL_TYPE_INT24

  • MYSQL_TYPE_DATE

  • MYSQL_TYPE_TIME

  • MYSQL_TYPE_DATETIME

  • MYSQL_TYPE_YEAR

  • MYSQL_TYPE_NEWDATE

  • MYSQL_TYPE_VARCHAR

  • MYSQL_TYPE_BIT

  • MYSQL_TYPE_TIMESTAMP2

  • MYSQL_TYPE_DATETIME2

  • MYSQL_TYPE_TIME2

  • MYSQL_TYPE_JSON

  • MYSQL_TYPE_NEWDECIMAL

  • MYSQL_TYPE_ENUM

  • MYSQL_TYPE_SET

  • MYSQL_TYPE_TINY_BLOB

  • MYSQL_TYPE_MEDIUM_BLOB

  • MYSQL_TYPE_LONG_BLOB

  • MYSQL_TYPE_BLOB

  • MYSQL_TYPE_VAR_STRING

  • MYSQL_TYPE_STRING

  • MYSQL_TYPE_GEOMETRY

  • STMT_INDICATOR_IGNORE

    Ignore the specified value

    STMT_INDICATOR_IGNORE_ROW

    Skip the current row

    UNIQUE_KEY_FLAG

    4

    Field is part of unique key

    MULTIPLE_KEY_FLAG

    8

    Field is part of a key

    BLOB_FLAG

    16

    Field is a blob

    UNSIGNED_FLAG

    32

    Field is unsigned integer

    ZEROFILL_FLAG

    64

    Field is zero filled

    BINARY_FLAG

    128

    Field is binary

    ENUM_FLAG

    256

    Field is enum

    AUTO_INCREMENT_FLAG

    512

    Field is an autoincrement field

    TIMESTAMP_FLAG

    1024

    Field is a timestamp

    SET_FLAG

    2048

    Field is a set

    NO_DEFAULT_VALUE_FLAG

    4096

    Field has no default value

    ON_UPDATE_NOW_FLAG

    8192

    If a field is updated it will get the current time value (NOW())

    NUM_FLAG

    32768

    Field is numeric

    SERVER_QUERY_NO_GOOD_INDEX_USED

    16

    SERVER_QUERY_NO_INDEX_USED

    32

    SERVER_STATUS_CURSOR_EXISTS

    64

    when using COM_STMT_FETCH, indicate that current cursor still has result

    SERVER_STATUS_LAST_ROW_SENT

    128

    when using COM_STMT_FETCH, indicate that current cursor has finished to send results

    SERVER_STATUS_DB_DROPPED

    1<<8

    database has been dropped

    SERVER_STATUS_NO_BACKSLASH_ESCAPES

    1<<9

    current escape mode is "no backslash escape"

    SERVER_STATUS_METADATA_CHANGED

    1<<10

    A DDL change did have an impact on an existing PREPARE (an automatic reprepare has been executed)

    SERVER_QUERY_WAS_SLOW

    1<<11

    Last statement took more than the time value specified in server variable long_query_time.

    SERVER_PS_OUT_PARAMS

    1<<12

    this resultset contain stored procedure output parameter

    SERVER_STATUS_IN_TRANS_READONLY

    1<<13

    current transaction is a read-only transaction

    SERVER_SESSION_STATE_CHANGED

    1<<14

    session state change. see Session change type for more information

    IS_LONGDATA(column_type)

    True if the column is a blob or text field

    STMT_INDICATOR_NTS

    String is zero terminated

    STMT_INDICATOR_NONE

    No indicator in use

    STMT_INDICATOR_NULL

    Value is NULL

    STMT_INDICATOR_DEFAULT

    Use default value

    Flag

    Value

    Description

    NOT_NULL_FLAG

    1

    Field can't be NULL

    PRI_KEY_FLAG

    2

    SERVER_STATUS_IN_TRANS

    1

    A transaction is currently active

    SERVER_STATUS_AUTOCOMMIT

    2

    Autocommit mode is set

    SERVER_MORE_RESULTS_EXIST

    8

    IS_PRI_KEY(flag)

    True if the field is part of a primary key

    IS_NOT_NULL(flags)

    True if the field is defined as not NULL

    IS_BLOB(flags)

    True if the field is a text or blob field

    IS_NUM(column_type)

    True if the column type is numeric

    enum enum_mysql_set_option

    enum enum_field_types

    enum mysql_enum_shutdown_level

    enum enum_stmt_attr_type

    enum enum_cursor_type

    enum enum_indicator_type

    Definitions

    Field Flags

    Server Status

    Macros

    mysql_set_server_option()
    mysql_server_shutdown()
    mysql_stmt_attr_set()
    mysql_stmt_attr_set()
    MYSQL_FIELD
    mariadb_get_infov()
    spinner

    Field is part of primary key

    more results exists (more packet follow)

    spinner

    Binlog/API Data Structures

    All structures and type definitions for the Binglog/Replication API are defined in include/mariadb_rpl.h.

    The following structures are used by the Binlog/Replication API:

    Structure
    Description

    MARIADB_STRING

    Stores a string together with its length.

    MARIADB_TIMESTAMP

    MARIADB_STRING is a simple structure that stores a string together with its length. It is equivalent to MYSQL_STRING and MYSQL_LEX_STRING.

    • str → Pointer to the character data.

    • length → Length of the string in bytes.

    MARIADB_TIMESTAMP stores timestamp values for MYSQL_TYPE_TIMESTAMP and MYSQL_TYPE_TIMESTAMP2 column data. It was introduced in MariaDB Connector/C 3.3.19 and 3.4.9 versions.

    • second → Represents the whole seconds portion of the timestamp.

    • second_part → Represents the fractional seconds (microseconds).

    MARIADB_GTID represents a Global Transaction ID (GTID).. A GTID uniquely specifies a transaction across a replication topology and is defined by three components: domain ID, server ID, and sequence number.

    • domain_id → The replication domain identifier.

    • server_id → The ID of the server that originally committed the transaction.

    • sequence_nr → The transaction’s sequence number within the domain.

    MARIADB_RPL is the generic replication handle. It represents a replication connection and is passed to all Binlog/Replication API calls.

    • The MARIADB_RPL structure is opaque. Its internal members should not be accessed directly.

    • To configure replication options, use mariadb_rpl_optionsv().

    • To retrieve replication options, use mariadb_rpl_get_optionsv()

    MARIADB_RPL_EVENT is the structure returned by mariadb_rpl_fetch() API function. It contains a common event header followed by a union of event-specific structures. The active union member is determined by the value of event_type.

    Field Validation

    • memroot → Internal memory pool used to allocate event data.

    • checksum → CRC32 checksum of the event (if binlog checksums are enabled).

    • ok → Non-zero if the event was received without error.

    The event union defines one member for each supported replication event type. Only the member that corresponds to the current event_type value contains valid data. The following sections describe each event type and its associated structure:

    ANNOTATE_ROWS_EVENT

    event_type value= 160 (0xA0)

    This event contains the statement that produced the subsequent row‑change event in the binary log stream. It is only generated if the client connects with the MARIADB_RPL_BINLOG_SEND_ANNOTATE_ROWS flag enabled.

    • statement → The SQL statement that triggered the row‑change event.

    Notes

    • ANNOTATE_ROWS_EVENT is sent only when the replication handle was opened with the MARIADB_RPL_BINLOG_SEND_ANNOTATE_ROWS flag, set through mariadb_rpl_optionsv().

    • If the flag is not set, this event will not be included in the binary log stream.

    BINLOG_CHECKPOINT_EVENT

    event_type value= 161 (0xA1)

    Written to the binary log to record the oldest binary log file that is still required for recovery. This event ensures that replication and recovery processes know which binary log files must be retained to guarantee consistency.

    • filename → The name of the oldest binary log file needed for crash recovery and replication consistency.

    START_ENCRYPTION_EVENT

    event_type value= 164 (0xA4)

    Written to the binary log when encryption is enabled on the source server. This event records the encryption scheme and key version used for subsequent event

    • scheme → Encryption scheme identifier.

    • key_version → Version of the encryption key used for encrypted log data.

    • nonce → Nonce (number used once) used in the encryption process.

    FORMAT_DESCRIPTION_EVENT

    event_type value= 15 (0x0F)

    Written at the beginning of every binary log file, at position 4. This event describes the format of all subsequent events in the file. For MariaDB 10.0 and later, the format field is always set to 4.

    • format → Binary log format version. Always 4 for MariaDB 10.0 and later.

    • server_version → Version string of the server that created the binary log.

    • timestamp

    GTID_EVENT

    event_type value= 162 (0xA2)

    Marks the start of a new global transaction event group. This event is written to the binary log before the events belonging to the transaction.

    • sequence_nr → Sequence number of the transaction within the replication domain.

    • domain_id → Identifier of the replication domain.

    • flags → Bitmask of event flags.

    Notes:

    • The GTID_EVENT ensures that each transaction is uniquely identified across the replication topology.

    • It captures all events belonging to the transaction, ensuring replication consumers can group and track them consistently.

    GTID_LIST_EVENT

    event_type value= 163 (0xA3)

    Written at the start of every binary log file to record the current replication state. This event contains the last GTID seen for each replication domain, allowing replicas to determine where to resume replication after a reconnect.

    • gtid_cnt → Number of GTID entries in the gtid array.

    • gtid → Array of MARIADB_GTID structures, one per replication domain.

    HEARTBEAT_LOG_EVENT

    event_type value= 27 (0x1B)

    Sent over the network by the source server to replicas when there are no binary log events to transmit. This event confirms that the source server is still alive. It is never written to the binary log file itself.

    • filename → Name of the current binary log file on the source server.

    INTVAR_EVENT

    event_type value=5 (0x05)

    Written to the binary log immediately before a QUERY_EVENT whenever the statement uses an AUTO_INCREMENT value or the LAST_INSERT_ID() function.

    • value → The integer value, either the next auto‑increment value or the result of LAST_INSERT_ID().

    • type → Indicates the variable type.

    Valid values for type are:

    Value
    Constant
    Description

    QUERY_EVENT

    event_type value=2 (0x02)

    Contains a SQL statement. This event is written to the binary log when:

    • The server binlog_format is set to STATEMENT (statement‑based replication).

    • A DDL statement is executed.

    • A COMMIT

    • thread_id → ID of the client thread that executed the statement on the source server.

    • seconds → Time in seconds that the statement took to execute.

    • database → Name of the default database at the time the statement was executed.

    RAND_EVENT

    event_type value=13 (0x0D)

    Written to the binary log immediately before a QUERY_EVENT that uses the RAND() function. This event records the seed values so that replicas can reproduce the same pseudo‑random sequence.

    • first_seed → First seed value for the RAND() function.

    • second_seed → Second seed value for the RAND() function.

    ROTATE_EVENT

    event_type value=4 (0x04)

    Written at the end of a binary log file to indicate that the next event will appear in a new binary log file.

    • position → Starting position in the new binary log file.

    • filename → Name of the new binary log file.

    Notes:

    • The ROTATE_EVENT signals the transition between binary log files, ensuring replication clients know where to continue reading.

    • It is always written at the end of a binary log file and points to the beginning of the next file.

    WRITE_ROWS_EVENT_V1, UPDATE_ROWS_EVENT_V1, DELETE_ROWS_EVENT_V1

    Event Types with values:

    • WRITE_ROWS_EVENT_V1 → 23 (0x17)

    • UPDATE_ROWS_EVENT_V1 → 24 (0x18)

    Row events are written to the binary log when the server binlog_format is set to ROW. All three event types share the same structure; the type field distinguishes the specific row operation (insert, update, or delete).

    • type → Row operation type: write (insert), update, or delete. See Replication API Types and Definitions.

    • table_id → References the table mapped by the preceding TABLE_MAP_EVENT.

    • flags

    TABLE_MAP_EVENT

    event_type value=19 (0x13)

    Written before each row event (in row‑based replication) to map a table ID to a fully qualified table name and provide column metadata for the rows that follow.

    • table_id → Numeric table ID used in subsequent row events to reference this table.

    • database → Name of the database containing the table.

    • table → Name of the table.

    USERVAR_EVENT

    event_type value=14 (0x0E)

    Written to the binary log before a QUERY_EVENT that references a user variable. This event records the variable’s name, type, and value so the replica can set it before executing the statement.

    • name → Name of the user variable.

    • is_null → Non‑zero if the variable’s value is NULL.

    • type

    XID_EVENT

    event_type value=16 (0x10)

    Written to the binary log when a transactional storage engine commits a transaction. This event records the XA transaction number and signals the end of the transaction’s event group.

    • transaction_nr → The XA transaction number for this commit.

    Notes:

    • The XID_EVENT marks the successful commit of a transaction in engines that support XA transactions.

    • It serves as the boundary marker for the transaction’s event group, ensuring replicas apply the transaction atomically.

    MariaDB Connector/C API Functions

    Explore API functions for MariaDB Connector/C. This section provides detailed documentation on functions for connecting, querying, and managing data, enabling robust C applications for MariaDB.

    The MariaDB Connector/C API provides functions for establishing connections, executing statements, retrieving and navigating result sets, managing transactions, and configuring connection options, plugins, and metadata.

    Function
    Description
    .

    event_type → Identifies the event type and determines which union member is active.

  • timestamp → Unix timestamp (seconds since epoch) when the event was created.

  • server_id → Server ID of the server that generated the event.

  • event_length → Total length of the event in bytes, including the header.

  • next_event_pos → Binary log position of the next event.

  • flags → Bitmask of event flags (see Replication API types and definitions for flag values).

  • → Unix timestamp of when the binary log file was created.
  • header_len → Length of the fixed event header in bytes.

  • post_header_lengths → Array of post‑header lengths for each event type. Added in Connector/C 3.3.5.

  • commit_id → Commit ID used to coordinate parallel replication.

  • format_id → Format identifier of the XA transaction, when the group commits an XA transaction.

  • gtrid_len → Length of the global transaction identifier part of the XID.

  • bqual_len → Length of the branch qualifier part of the XID.

  • xid → XA transaction identifier associated with the transaction.

  • is issued for a non‑transactional storage engine.

    errornr → Error number if the statement produced an error; 0 on success.

  • status → Status variables blob (encoded server status at the time of execution).

  • statement → The SQL statement text.

  • DELETE_ROWS_EVENT_V1
    →
    25 (0x19)
    → Row event flags bitmask.
  • column_count → Number of columns in the table.

  • column_bitmap → Bitmap of columns present in the row image; one bit per column.

  • column_update_bitmap → For UPDATE_ROWS_EVENT: bitmap of columns present in the after‑image. NULL for write and delete events.

  • null_bitmap → Bitmap indicating which columns hold a NULL value in the row image.

  • row_data_size → Size in bytes of row_data.

  • row_data → Raw encoded row data. Use mariadb_rpl_extract_rows() to decode.

  • extra_data_size → Size in bytes of extra_data.

  • extra_data → Raw encoded extra row-event data, when present.

  • compressed → Non‑zero if the row data is compressed.

  • row_count → Number of rows contained in the event.

  • column_count → Number of columns in the table.

  • column_types → Array of column type identifiers, one byte per column.

  • metadata → Type‑specific metadata for each column (length varies by column type).

  • null_indicator → Bitmap indicating which columns are nullable; one bit per column.

  • signed_indicator → Bitmap indicating which numeric columns are signed.

  • column_names → Optional metadata listing the column names.

  • geometry_types → Optional metadata listing the geometry subtypes for spatial columns.

  • default_charset → Default character set applied to string columns.

  • column_charsets → Optional metadata listing per‑column character sets.

  • simple_primary_keys → Optional metadata listing primary-key columns without a prefix length.

  • prefixed_primary_keys → Optional metadata listing primary-key columns that use a prefix length.

  • set_values → Optional metadata listing the possible values for SET columns.

  • enum_values → Optional metadata listing the possible values for ENUM columns.

  • enum_set_default_charset → Default character set applied to ENUM and SET columns.

  • enum_set_column_charsets → Optional metadata listing per‑column character sets for ENUM and SET columns.

  • → Data type of the variable value.
  • charset_nr → Collation ID for string values.

  • value → Encoded value of the variable. Empty if is_null is non‑zero.

  • flags → Reserved flags field.

  • Stores a timestamp value used in MYSQL_TYPE_TIMESTAMP and MYSQL_TYPE_TIMESTAMP2 columns.

    MARIADB_GTID

    Stores a global transaction ID (domain ID, server ID, and sequence number).

    MARIADB_RPL

    Opaque replication handle representing a replication connection.

    MARIADB_RPL_EVENT

    Contains a common event header and a union of all event-specific structures returned by mariadb_rpl_fetch().

    0x01

    LAST_INSERT_ID

    Value is the result of LAST_INSERT_ID().

    0x02

    INSERT_ID

    Value is the next AUTO_INCREMENT value.

    MARIADB_STRING

    MARIADB_TIMESTAMP

    MARIADB_GTID

    MARIADB_RPL

    Events

    MARIADB_RPL_EVENT

    Event Union Behavior

    • Encrypted event data is available only when reading directly from a binary log file.

    • When a client connects to a live source server, the server always sends unencrypted events, even if encryption is enabled at rest.

    • This event always appears at the start of a binary log file (position 4).

    • It defines the structure and header lengths for all subsequent events, ensuring compatibility between server and client replication components.

    • The GTID_LIST_EVENT provides a snapshot of the replication state at the beginning of a binary log file.

    • By recording the last GTID for each domain, it ensures replicas can safely resume replication after interruptions.

    • QUERY_EVENT is central to statement‑based replication, ensuring that SQL statements are replayed consistently on replicas.

    • Even in row‑based replication, certain operations (like DDL or non‑transactional commits) still generate QUERY_EVENT entries.

    • The RAND_EVENT ensures deterministic replication of statements that rely on pseudo‑random values.

    • By recording both seed values, replicas can generate the same sequence of random numbers as the source server, maintaining consistency across the replication topology.

    See Also

    MariaDB Binlog/Replication API Reference
    Replication API Types and Definitions
    Replication API Function Reference
    typedef struct {
      char *str;
      size_t length;
    } MARIADB_STRING;
    typedef struct {
      uint32_t second;
      uint32_t second_part;
    } MARIADB_TIMESTAMP;
    typedef struct st_mariadb_gtid {
      unsigned int domain_id;
      unsigned int server_id;
      unsigned long long sequence_nr;
    } MARIADB_GTID;
    typedef struct st_mariadb_rpl_event
    {
      /* common header */
      MA_MEM_ROOT memroot;
      unsigned int checksum;
      char ok;
      enum mariadb_rpl_event event_type;
      unsigned int timestamp;
      unsigned int server_id;
      unsigned int event_length;
      unsigned int next_event_pos;
      unsigned short flags;
      /****************/
      union {
        struct st_mariadb_rpl_rotate_event rotate;
        struct st_mariadb_rpl_query_event query;
        struct st_mariadb_rpl_format_description_event format_description;
        struct st_mariadb_rpl_gtid_list_event gtid_list;
        struct st_mariadb_rpl_checkpoint_event checkpoint;
        struct st_mariadb_rpl_xid_event xid;
        struct st_mariadb_rpl_gtid_event gtid;
        struct st_mariadb_rpl_annotate_rows_event annotate_rows;
        struct st_mariadb_rpl_table_map_event table_map;
        struct st_mariadb_rpl_rand_event rand;
        struct st_mariadb_rpl_intvar_event intvar;
        struct st_mariadb_rpl_uservar_event uservar;
        struct st_mariadb_rpl_rows_event rows;
        struct st_mariadb_rpl_heartbeat_event heartbeat;
        /* The following events were added in version 3.3.5 */
        struct st_mariadb_rpl_xa_prepare_log_event xa_prepare_log;
        struct st_mariadb_begin_load_query_event begin_load_query;
        struct st_mariadb_execute_load_query_event execute_load_query;
        struct st_mariadb_gtid_log_event gtid_log;
        struct st_mariadb_start_encryption_event start_encryption;
        struct st_mariadb_rpl_previous_gtid_event previous_gtid;
      } event;
    } MARIADB_RPL_EVENT;
    struct st_mariadb_rpl_annotate_rows_event {
      MARIADB_STRING statement;
    };
    struct st_mariadb_rpl_checkpoint_event {
      MARIADB_STRING filename;
    };
    struct st_mariadb_start_encryption_event {
      uint8_t scheme;
      uint32_t key_version;
      char nonce[12];
    };
    struct st_mariadb_rpl_format_description_event
    {
      uint16_t format;
      char *server_version;
      uint32_t timestamp;
      uint8_t header_len;
      /* Added in 3.3.5 */
      MARIADB_STRING post_header_lengths;
    };
    struct st_mariadb_rpl_gtid_event {
      uint64_t sequence_nr;
      uint32_t domain_id;
      uint8_t flags;
      uint64_t commit_id;
      uint32_t format_id;
      uint8_t gtrid_len;
      uint8_t bqual_len;
      MARIADB_STRING xid;
    };
    struct st_mariadb_rpl_gtid_list_event {
      uint32_t gtid_cnt;
      MARIADB_GTID *gtid;
    };
    struct st_mariadb_rpl_heartbeat_event {
      MARIADB_STRING filename;
    };
    struct st_mariadb_rpl_intvar_event {
      unsigned long long value;
      uint8_t type;
    };
    struct st_mariadb_rpl_query_event {
      uint32_t thread_id;
      uint32_t seconds;
      MARIADB_STRING database;
      uint32_t errornr;
      MARIADB_STRING status;
      MARIADB_STRING statement;
    };
    struct st_mariadb_rpl_rand_event {
      unsigned long long first_seed;
      unsigned long long second_seed;
    };
    struct st_mariadb_rpl_rotate_event {
      unsigned long long position;
      MARIADB_STRING filename;
    };
    struct st_mariadb_rpl_rows_event {
      enum mariadb_row_event_type type;
      uint64_t table_id;
      uint16_t flags;
      uint32_t column_count;
      unsigned char *column_bitmap;
      unsigned char *column_update_bitmap;
      unsigned char *null_bitmap;
      size_t row_data_size;
      void *row_data;
      size_t extra_data_size;
      void *extra_data;
      uint8_t compressed;
      uint32_t row_count;
    };
    struct st_mariadb_rpl_table_map_event {
      unsigned long long table_id;
      MARIADB_STRING database;
      MARIADB_STRING table;
      uint32_t column_count;
      MARIADB_STRING column_types;
      MARIADB_STRING metadata;
      unsigned char *null_indicator;
      unsigned char *signed_indicator;
      MARIADB_CONST_DATA column_names;
      MARIADB_CONST_DATA geometry_types;
      uint32_t default_charset;
      MARIADB_CONST_DATA column_charsets;
      MARIADB_CONST_DATA simple_primary_keys;
      MARIADB_CONST_DATA prefixed_primary_keys;
      MARIADB_CONST_DATA set_values;
      MARIADB_CONST_DATA enum_values;
      uint8_t enum_set_default_charset;
      MARIADB_CONST_DATA enum_set_column_charsets;
    };
    struct st_mariadb_rpl_uservar_event {
      MARIADB_STRING name;
      uint8_t is_null;
      uint8_t type;
      uint32_t charset_nr;
      MARIADB_STRING value;
      uint8_t flags;
    };
    struct st_mariadb_rpl_xid_event {
      uint64_t transaction_nr;
    };

    Connect to a database server using a connection string.

    Checks whether the client is currently connected to a MariaDB or MySQL server.

    Converts a string to a different character set.

    Returns extended metadata for pluggable field types such as JSON and GEOMETRY.

    Retrieves generic or connection-related information.

    Retrieves generic or connection-specific information from a MariaDB Connector/C handle, accepting a value-type enum and a pointer to store the result.

    Attempts to re-establish a dropped MariaDB Connector/C connection using the original credentials, and requires the MYSQL_OPT_RECONNECT option to be set.

    Returns the number of rows affected by the last INSERT, UPDATE, DELETE, or REPLACE statement executed on a MariaDB Connector/C connection.

    Enables or disables autocommit mode for the current database connection, returning zero on success or nonzero on failure.

    Changes the authenticated user and default database on an existing connection, resetting session state including transactions, temporary tables, and locks.

    Returns the name of the default client character set for a specified MariaDB Connector/C connection.

    Returns a handle to an already-loaded client plugin of the given name and type.

    Terminates an open database connection and releases the memory allocated for the MYSQL handle.

    Commits the current transaction on a MariaDB Connector/C connection, returning zero on success without affecting autocommit mode.

    Moves the result set pointer to an arbitrary row offset in a buffered result set obtained via mysql_store_result, enabling random row access.

    Enables debug output for a MariaDB Connector/C client using the DBUG library, accepting a colon-separated control string to configure trace and logging options.

    Instructs a MariaDB server to write connection status information to the error log, and requires the SUPER privilege for the current user.

    Determines whether the final row in a result set has already been retrieved. (Deprecated.)

    Returns the numeric error code from the most recent MariaDB Connector/C function call, or zero if no error occurred.

    Returns the error message string for the most recent failed MariaDB Connector/C function call, or an empty string if no error occurred.

    Encodes a string using the default character set for safe use in SQL statements. Deprecated — use mysql_real_escape_string instead.

    Returns the definition of one result set column as a MYSQL_FIELD pointer; call it repeatedly to iterate over all columns in the result set.

    Returns a MYSQL_FIELD pointer for a specific column in a result set, identified by its zero-based field number.

    Returns all column definitions for a MariaDB result set as an array of MYSQL_FIELD structures, one entry per column.

    Returns an array of byte lengths for each column in the current row of a MariaDB result set, valid only after mysql_fetch_row is called.

    Retrieves the next row from a MariaDB result set as an array of char pointers, returning NULL when no more rows are available.

    Returns the number of columns in the most recent query result for a MariaDB connection, useful for checking whether a result set is available.

    Sets the field cursor to a given column offset in a MariaDB result set, controlling which field mysql_fetch_field returns next.

    Retrieves the current field cursor position in a result set, which can be passed to mysql_field_seek to restore that position.

    Releases the memory allocated for a MariaDB result set; row values obtained from prior mysql_fetch_row calls become invalid after this call.

    Populates a MY_CHARSET_INFO structure with details about the current default character set for a MariaDB Connector/C connection.

    Retrieves the client library version as a string; use mysql_get_client_version for the equivalent numeric value.

    Retrieves the client library version as an unsigned long; use mysql_get_client_info for the string representation.

    Returns a string describing the connection type and server hostname for a MariaDB Connector/C connection, or NULL if invalid.

    Retrieves the current value of a connection option previously set with mysql_optionsv, supporting boolean, integer, string, and miscellaneous option types.

    Returns the protocol version number used for a MariaDB Connector/C connection; versions 9 and below are not supported.

    Retrieves the connected server version string; use mysql_get_server_version for the equivalent numeric representation.

    Retrieves the server version as an unsigned long; use mysql_get_server_info for the equivalent string representation.

    Returns the name of the TLS cipher in use for a MariaDB Connector/C connection, or NULL for non-TLS connections.

    Retrieves the timeout value configured for asynchronous operations, in seconds.

    Retrieves the timeout value configured for asynchronous operations, in milliseconds.

    Converts a binary buffer to a hex-encoded string for safe embedding in SQL; the output buffer must be at least 2*length+1 bytes.

    Returns a string with summary statistics about the last executed query, covering INSERT, UPDATE, ALTER TABLE, and LOAD DATA operations; returns NULL for SELECT.

    Allocates and initializes a MYSQL structure for use with mysql_real_connect, and also initializes the thread subsystem if not already done.

    Returns the AUTO_INCREMENT value generated by the last INSERT or UPDATE statement on a MariaDB connection, or zero if no such value was produced.

    Requests the MariaDB server to terminate the thread with the given process ID; use mysql_thread_id to obtain the ID of the current connection.

    Loads a client plugin of the given name and type from the client plugin directory.

    Finalizes the MariaDB Connector/C library after use, performing memory cleanup and shutting down the embedded server if applicable.

    Initializes the MariaDB Connector/C library before any other functions are called, starting the embedded server if used in that configuration.

    Indicates whether additional result sets remain from a previous multi-statement query, returning 1 if more results are available.

    Returns the length of a length-encoded field and advances the pointer past it.

    Reads the next protocol packet from the server into the connection's network buffer.

    Advances to the next result set from a multi-statement query, making it available for retrieval via mysql_store_result or mysql_use_result.

    Retrieves the column count from a result set handle, useful for iterating over fields in a MariaDB query result.

    Returns the number of rows in a MariaDB result set; for unbuffered results the count is only accurate after all rows have been fetched.

    Sets extra connection options that take two arguments; call after mysql_init() and before mysql_real_connect().

    Sets extra connection options on a MYSQL handle before calling mysql_real_connect. Deprecated since Connector/C 3.0 — use mysql_optionsv instead.

    Sets connection, TLS, plugin, and option-file options on a MariaDB Connector/C handle before mysql_real_connect, supporting a variable argument list.

    Checks whether a MariaDB server connection is still active and attempts an automatic reconnect if the connection has dropped and reconnect is enabled.

    Sends a null-terminated SQL string to the MariaDB server for execution, returning zero on success; use mysql_real_query for binary-safe operation.

    Reads the result of a statement previously sent with mysql_send_query, and must be called once for each successful mysql_send_query call.

    Opens a connection to a MariaDB server and returns a MYSQL handle on success, or NULL if the connection could not be established.

    Encodes a string for safe use in a SQL statement, taking the connection's current character set into account when escaping special characters.

    Sends a binary-safe SQL statement to a MariaDB server; use mysql_num_fields to determine whether the query returned a result set.

    Flushes server-side caches and state using a bitmask of options such as REFRESH_GRANT, REFRESH_LOG, REFRESH_TABLES, and REFRESH_HOSTS.

    Resets session state on a MariaDB Connector/C connection — rolling back transactions and clearing variables — without disconnecting or reauthenticating.

    Undoes the current transaction for a database connection; it has no effect if autocommit is enabled or the engine is non-transactional.

    Repositions the row cursor in a buffered MariaDB result set to an arbitrary offset, returning the previous row position as a MYSQL_ROW_OFFSET.

    Returns the current row cursor offset for a buffered MariaDB result set, which can then be passed to mysql_row_seek to restore that position.

    Changes the default database on an active connection; the current default can also be queried with the SELECT DATABASE() SQL function.

    Dispatches a query asynchronously on a MariaDB connection; each call must be followed by mysql_read_query_result to consume the response.

    Is an alias for mysql_library_end in MariaDB Connector/C, used to finalize and clean up the client library.

    Is an alias for mysql_library_init in MariaDB Connector/C, used to initialize the client library before making any other calls.

    Retrieves the first session state change notification from the server, covering schema changes, system variables, and state flags. Added in Connector/C 3.0.

    Retrieves subsequent session state change notifications after mysql_session_track_get_first, called repeatedly until a nonzero value signals end of data.

    Sets the default character set for a MariaDB Connector/C connection, ensuring mysql_real_escape_string uses the correct encoding.

    Enables or disables multi-statement support on a MariaDB connection using MYSQL_OPTION_MULTI_STATEMENTS_ON or _OFF.

    Registers custom callback functions for init, read, end, and error phases of a LOAD DATA LOCAL INFILE operation in MariaDB Connector/C.

    Resets local infile callbacks to the Connector/C internal defaults, reversing any custom handler registered via mysql_set_local_infile_handler.

    Sends a shutdown request to the MariaDB server over the current connection, requiring the SHUTDOWN privilege for the authenticated user.

    Returns the five-character SQLSTATE error code for the most recent MariaDB Connector/C function call, with 00000 indicating success.

    Configures TLS parameters including key, certificate, CA, and cipher list for a MariaDB connection, and must be called before mysql_real_connect.

    Returns a status string from the MariaDB server covering uptime, active threads, query count, open tables, and queries per second.

    Retrieves a complete buffered result set from the last executed MariaDB query, returning NULL on error or for non-SELECT statements.

    Releases thread-local memory allocated by mysql_thread_init and must be called explicitly before a thread exits to avoid memory leaks. Deprecated in Connector/C 3.0.

    Retrieves the thread identifier for an active connection; the value may change after a reconnect if the reconnect option is enabled.

    Initializes thread-local variables for multi-threaded Connector/C clients; called automatically by mysql_init if not invoked explicitly. Deprecated in Connector/C 3.0.

    Returns 1 if the MariaDB Connector/C client library was compiled with thread-safety support, or zero otherwise.

    Initiates unbuffered retrieval of a query result set row by row from the MariaDB server, blocking the connection until all rows are fetched or freed.

    Retrieves the warning count from the most recent query execution; use SHOW WARNINGS for the full warning message text.

    mariadb_cancel()

    Immediately aborts a connection by making all subsequent read/write operations fail, without freeing the MYSQL structure or closing communication channels.

    Function Overview

    mysql_optionsv

    mysql_optionsv sets connection, TLS, plugin, and option-file options on a MariaDB Connector/C handle before mysql_real_connect, supporting a variable argument list.

    • mysql - a mysql handle, which was previously allocated by or .

    • mysql_option - the option to set. See description below.

    mariadb_connect()
    mariadb_connection()
    mariadb_convert_string()
    mariadb_field_attr()
    mariadb_get_info()
    mariadb_get_infov()
    mariadb_reconnect()
    mysql_affected_rows()
    mysql_autocommit()
    mysql_change_user()
    mysql_character_set_name()
    mysql_client_find_plugin()
    mysql_close()
    mysql_commit()
    mysql_data_seek()
    mysql_debug()
    mysql_dump_debug_info()
    mysql_eof()
    mysql_errno()
    mysql_error()
    mysql_escape_string()
    mysql_fetch_field()
    mysql_fetch_field_direct()
    mysql_fetch_fields()
    mysql_fetch_lengths()
    mysql_fetch_row()
    mysql_field_count()
    mysql_field_seek()
    mysql_field_tell()
    mysql_free_result()
    mysql_get_character_set_info()
    mysql_get_client_info()
    mysql_get_client_version()
    mysql_get_host_info()
    mysql_get_optionv()
    mysql_get_proto_info()
    mysql_get_server_info()
    mysql_get_server_version()
    mysql_get_ssl_cipher()
    mysql_get_timeout_value()
    mysql_get_timeout_value_ms()
    mysql_hex_string()
    mysql_info()
    mysql_init()
    mysql_insert_id()
    mysql_kill()
    mysql_load_plugin()
    mysql_library_end()
    mysql_library_init()
    mysql_more_results()
    mysql_net_field_length()
    mysql_net_read_packet()
    mysql_next_result()
    mysql_num_fields()
    mysql_num_rows()
    mysql_options4()
    mysql_options()
    mysql_optionsv()
    mysql_ping()
    mysql_query()
    mysql_read_query_result()
    mysql_real_connect()
    mysql_real_escape_string()
    mysql_real_query()
    mysql_refresh()
    mysql_reset_connection()
    mysql_rollback()
    mysql_row_seek()
    mysql_row_tell()
    mysql_select_db()
    mysql_send_query()
    mysql_server_end()
    mysql_server_init()
    mysql_session_track_get_first()
    mysql_session_track_get_next()
    mysql_set_character_set()
    mysql_set_server_option()
    mysql_set_local_infile_handler()
    mysql_set_local_infile_default()
    mysql_shutdown()
    mysql_sqlstate()
    mysql_ssl_set()
    mysql_stat()
    mysql_store_result()
    mysql_thread_end()
    mysql_thread_id()
    mysql_thread_init()
    mysql_thread_safe()
    mysql_use_result()
    mysql_warning_count()

    arg - the value for the option.

  • ... - variable argument list.

  • Used to set extra connect options and affect behavior for a connection. This function may be called multiple times to set several options. All calls pass numeric literal values for a const void *. mysql_optionsv() should be called after mysql_init().

    Some of these options can also be set in option files, such as my.cnf.

    Returns zero on success, non-zero if an error occurred (invalid option or value).

    The following table shows the C variable type required for the arg parameter of each option:

    Variable type
    Options

    my_bool, unsigned char

    MYSQL_OPT_RECONNECT, MYSQL_SECURE_AUTH, MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_SSL_ENFORCE, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, MARIADB_OPT_SKIP_READ_RESPONSE, MYSQL_OPT_ZSTD_COMPRESSION_LEVEL

    unsigned int

    MARIADB_OPT_PORT, MYSQL_OPT_LOCAL_INFILE, MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_PROTOCOL, MYSQL_OPT_READ_TIMEOUT, MYSQL_OPT_WRITE_TIMEOUT

    unsigned long

    MYSQL_OPT_NET_BUFFER_LENGTH, MYSQL_OPT_MAX_ALLOWED_PACKET

    • MYSQL_INIT_COMMAND: lets you specify a command to execute immediately after connecting (and also after a reconnect if enabled).

      mysql_optionsv(mysql, MYSQL_INIT_COMMAND, (void *)"CREATE TABLE test.t1(a int)");
      mysql_optionsv(mysql, MYSQL_INIT_COMMAND, (void *)"SET @value := 1");
      • Each call adds one SQL statement to an internal list; all stored commands are executed in order.

      • You cannot concatenate multiple statements with semicolons; each statement must be added with a separate call.

      Note: When multiple option files are used, init_command entries are aggregated from all files read (for example, /etc/my.cnf and ~/.my.cnf). The resulting combined list of statements executes on every connection and reconnection, without any clear indication that they originated from different sources. If unexpected statements run during a connection, review all active option files to identify their source.

    • MYSQL_OPT_CONNECT_TIMEOUT: Connect timeout in seconds. This value will be passed as an unsigned int parameter.

    • MYSQL_PROGRESS_CALLBACK: Specifies a callback function which will be able to visualize the progress of certain long running statements (i.e. or ).

    • MYSQL_OPT_RECONNECT: Enable or disable automatic reconnect.

    • MYSQL_OPT_READ_TIMEOUT: Specifies the timeout in seconds for reading packets from the server.

    • MYSQL_OPT_WRITE_TIMEOUT: Specifies the timeout in seconds for sending packets to the server.

    • MYSQL_REPORT_DATA_TRUNCATION: Enable or disable reporting data truncation errors for prepared statements.

    • MYSQL_SET_CHARSET_DIR: files.

    • MYSQL_SET_CHARSET_NAME: Specify the default for the connection.

    • MYSQL_OPT_BIND: Specify the network interface from which to connect to MariaDB Server.

    • MYSQL_OPT_NONBLOCK: Specify stack size for non-blocking operations. The argument for MYSQL_OPT_NONBLOCK is the size of the stack used to save the state of a non-blocking operation while it is waiting for I/O and the application is doing other processing. Normally, applications will not have to change this, and it can be passed as zero to use the default value.

    • MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS: If this option is set, the client indicates that it will be able to handle expired passwords by setting the CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS capability flag. If the password has expired and CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS is set, the server will not return an error when connecting, but put the connection in sandbox mode, where all commands will return error 1820 (ER_MUST_CHANGE_PASSWORD) unless a new password was set. This option was added in MariaDB Connector/C 3.0.4

    • MYSQL_OPT_MAX_ALLOWED_PACKET: The maximum packet length to send to or receive from server. The default is 16MB, the maximum 1GB.

    • MYSQL_OPT_NET_BUFFER_LENGTH: The buffer size for TCP/IP and socket communication. Default is 16KB.

    Some of these options can also be set as arguments to the mysql_real_connect function.

    • MARIADB_OPT_HOST: Hostname or IP address of the server to connect to.

      mysql_optionsv(mysql, MARIADB_OPT_HOST, (void *)"dbserver.example.com");
    • MARIADB_OPT_USER: User to login to the server.

      mysql_optionsv(mysql, MARIADB_OPT_USER, (void *)"myuser");
    • MARIADB_OPT_PASSWORD: Password of the user to login to the server.

      mysql_optionsv(mysql, MARIADB_OPT_PASSWORD, (void *)"horsebattery");
    • MARIADB_OPT_SCHEMA: Database to use.

    • MARIADB_OPT_PORT: Port number to use for connection.

    • MARIADB_OPT_UNIXSOCKET: For connections to localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.

    • MYSQL_OPT_NAMED_PIPE: For Windows operating systems only: Use named pipes for client/server communication.

    • MYSQL_OPT_PROTOCOL: Specify the type of client/server protocol. Possible values are:

      • MYSQL_PROTOCOL_TCP

      • MYSQL_PROTOCOL_SOCKET

    • MARIADB_OPT_FOUND_ROWS: Return the number of matched rows instead of number of changed rows.

    • MYSQL_OPT_COMPRESS: Use the compressed protocol for client server communication. If the server doesn't support compressed protocol, the default protocol will be used.

    • MYSQL_OPT_ZSTD_COMPRESSION_LEVEL: The compression level to use for connections that use the zstd compression algorithm. Acceptable values are integers in the range 1 (fastest) to 22 (maximum compression). This option has no effect if zstd compression is not in use. Added in MariaDB Connector/C 3.3.14 and 3.4.4 versions.

    • MYSQL_OPT_LOCAL_INFILE: Enable or disable the use of

    • MARIADB_OPT_MULTI_STATEMENTS: Allows the client to send multiple statements in one command. Statements will be divided by a semicolon.

    • MARIADB_OPT_MULTI_RESULTS: Indicates that the client is able to handle multiple result sets from stored procedures or multi statements. This option will be automatically set if MARIADB_OPT_MULTI_STATEMENTS is set.

    • MYSQL_SHARED_MEMORY_BASE_NAME: Shared-memory name to use for Windows connections using shared memory to a local server (started with the --shared-memory option). Case-sensitive.

    • MYSQL_OPT_SSL_KEY: Defines a path to a private key file to use for . This option requires that you use the absolute path, not a relative path. If the key is protected with a passphrase, the passphrase needs to be specified with MARIADB_OPT_TLS_PASSPHRASE option.

      mysql_optionsv(mysql, MYSQL_OPT_SSL_KEY, (void *)"certs/client-key.pem");
    • MYSQL_OPT_SSL_CERT: Defines a path to the X509 certificate file to use for . This option requires that you use the absolute path, not a relative path.

      mysql_optionsv(mysql, MYSQL_OPT_SSL_CERT, (void *)"certs/client-cert.pem");
    • MYSQL_OPT_SSL_CA: Defines a path to a PEM file that should contain one or more X509 certificates for trusted Certificate Authorities (CAs) to use for . This option requires that you use the absolute path, not a relative path. See for more information.

    • MYSQL_OPT_SSL_CAPATH: Defines 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 for . This option requires that you use the absolute path, not a relative path. The directory specified by this option needs to be run through the command. See for more information. This option is only supported if the connector was built with OpenSSL. If the connector was built with GnuTLS or Schannel, then this option is not supported. See for more information about which libraries are used on which platforms.

    • MYSQL_OPT_SSL_CIPHER: Defines a list of permitted ciphers or cipher suites to use for .

    • MYSQL_OPT_SSL_CRL: Defines a path to a PEM file that should contain one or more revoked X509 certificates to use for . This option requires that you use the absolute path, not a relative path. See for more information. This option is only supported if the connector was built with OpenSSL or Schannel. If the connector was built with GnuTLS, then this option is not supported. See for more information about which libraries are used on which platforms.

    • MYSQL_OPT_SSL_CRLPATH: Defines a path to a directory that contains one or more PEM files that should each contain one revoked X509 certificate to use for . This option requires that you use the absolute path, not a relative path. The directory specified by this option needs to be run through the command. See for more information. This option is only supported if the connector was built with OpenSSL. If the connector was built with GnuTLS or Schannel, then this option is not supported. See for more information about which libraries are used on which platforms.

    • MARIADB_OPT_SSL_FP: Specify the fingerprint hash of a server certificate for validation during the handshake. Before version 3.4.0, Connector/C accepted only SHA1 hashes. Starting with version 3.4.0, support was extended to include SHA256, SHA384, and SHA512. This option is deprecated. Use MARIADB_OPT_TLS_PEER_FP instead.

    • MARIADB_OPT_TLS_PEER_FP: Specify the SHA1 fingerprint of a server certificate for validation during the handshake.

    • MARIADB_OPT_SSL_FP_LIST: Specify a file containing one or more fingerprint hashes of server certificates for validation during the handshake. Before version 3.4.0, Connector/C accepted only SHA1 hashes. Starting with version 3.4.0, support was extended to include SHA256, SHA384, and SHA512. This is deprecated. Use MARIADB_OPT_TLS_PEER_FP_LIST instead.

    • MARIADB_OPT_TLS_PEER_FP_LIST: Specify a file which contains one or more SHA1 fingerprints of server certificates for validation during the handshake.

    • MARIADB_OPT_TLS_PASSPHRASE: Specify a passphrase for a passphrase-protected private key, as configured by the MYSQL_OPT_SSL_KEY option. This option is only supported if the connector was built with OpenSSL or GnuTLS. If the connector was built with Schannel, then this option is not supported. See for more information about which libraries are used on which platforms.

    • MARIADB_OPT_TLS_VERSION: Defines which protocol versions are allowed. This should be a comma-separated list of TLS protocol versions to allow. Valid TLS protocol versions are TLSv1.0, TLSv1.1, TLSv1.2, and TLSv1.3. Both the client and server should support the allowed TLS protocol versions. See for information on which TLS libraries support which TLS protocol versions. See for more information about which TLS libraries are used on which platforms.

    • MYSQL_OPT_SSL_VERIFY_SERVER_CERT: Enables (or disables) .

    • MYSQL_OPT_SSL_ENFORCE: Enables using the default system settings. Does not require TLS certificates, keys, or CAs to be explicitly configured.

    • Note: Despite the option name, this does not enforce TLS. If the server does not support TLS, the connection falls back to unencrypted communication without error. To prevent fallback and enforce TLS, use MYSQL_OPT_SSL_VERIFY_SERVER_CERT instead.

    • MARIADB_OPT_TLS_CIPHER_STRENGTH: Deprecated. This option is no longer in use and has no effect. Cipher strength. This value will be passed as an unsigned int parameter.

    • MYSQL_DEFAULT_AUTH: Default authentication client-side plugin to use.

      mysql_optionsv(mysql, MYSQL_DEFAULT_AUTH, (void *)"ed25519");
    • MYSQL_ENABLE_CLEARTEXT_PLUGIN: This option is supported to be compatible with MySQL client libraries. MySQL client libraries use this option to determine whether the authentication plugin can be used. However, MariaDB clients and client libraries do not need to set any options in order to use this authentication plugin. Therefore, this option does not actually do anything in MariaDB Connector/C.

      mysql_optionsv(mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, 1);
    • MARIADB_OPT_CONNECTION_HANDLER: Specify the name of a connection handler plugin.

    • MARIADB_OPT_RESTRICTED_AUTH: Specifies a comma-separated list of authentication plugins that are permitted for authenticating this connection. If the server requests an authentication plugin that is not in this list, MariaDB Connector/C returns an error and the connection is refused. This option can be used to prevent the use of weaker authentication methods. Added in MariaDB Connector/C 3.3.0 version.

    • MARIADB_OPT_USERDATA: Bundle user data to the current connection, e.g. for use in connection handler plugins. This option requires 4 parameters: connection, option, key and value.

    • MARIADB_OPT_CONNECTION_READ_ONLY: This option is used by connection handler plugins and indicates that the current connection will be used for read operations only.

    • MARIADB_OPT_SKIP_READ_RESPONSE: Disables server response packet reading in the binary protocol. Designed for specialized connection handlers, not for typical application use. Added in Connector/C 3.1.13 version.

    • MYSQL_PLUGIN_DIR: Specify the location of client plugins. The plugin directory can also be specified with the MARIADB_PLUGIN_DIR environment variable.

    • MYSQL_SECURE_AUTH: Refuse to connect to the server if the server uses the authentication plugin. This mode is off by default, which is a difference in behavior compared to MySQL 5.6 and later, where it is on by default.

    • MYSQL_SERVER_PUBLIC_KEY: Specifies 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 client authentication plugin. It was introduced in Connector/C 3.1.0.

    • MARIADB_OPT_STATUS_CALLBACK: Specifies a callback function that is invoked whenever the server sends a status change or session tracking information to the client. This can be used to monitor server status flags and session variable changes without polling.

      mysql_optionsv(mysql, MARIADB_OPT_STATUS_CALLBACK, (void *)my_status_callback, (void *)user_data);

      The callback function must match the following signature:

      void status_callback(void *data, enum enum_mariadb_status_info type, ..)

    Parameters

    Parameter
    Type
    Description

    data

    void *

    The pointer passed as the second argument when registering the callback (typically a connection handle or application context)

    type

    enum enum_mariadb_status_info

    Indicates the category of information being delivered. Either STATUS_TYPE or SESSION_TRACK_TYPE.

    Variadic Parameters (vary by type)

    When type is STATUS_TYPE:

    Position
    Type
    Description

    1st

    unsigned int

    The current server status flags.

    When type is SESSION_TRACK_TYPE:

    Position
    Type
    Description

    1st

    enum enum_session_state_type

    The session tracking type.

    2nd

    MARIADB_CONST_STRING *

    If track_type is SESSION_TRACK_SYSTEM_VARIABLES: the variable name.

    An example implementation can be found in the Connector/C source tree at unittest/libmariadb/connection.c (function test_status_callback). Added in MariaDB Connector/C 3.3.2 version.

    • MARIADB_OPT_RPL_REGISTER_REPLICA: Specifies the host name and port that the Binlog API will report when registering this client as a replica with the connected server. When this option is set, mariadb_rpl_open() will register the client using the provided host, port, and the server ID configured via mariadb_rpl_optionsv(). The registration is visible in the output of SHOW SLAVE STATUS on the server.

      mysql_optionsv(mysql, MARIADB_OPT_RPL_REGISTER_REPLICA, (void *)"replica-host.example.com", (unsigned int)3306);

      Added in MariaDB Connector/C 3.3.1 version. See Replication API Reference.

    • MYSQL_READ_DEFAULT_FILE: Read options from an option file.

    • MYSQL_READ_DEFAULT_GROUP: Read options from the named option group from an option file.

    These options work together, according to the following rules:

    • if both are set to NULL, then no option files are read.

    • if MYSQL_READ_DEFAULT_FILE is set to an empty string (or NULL and MYSQL_READ_DEFAULT_GROUP is set) then all default option files are read.

    • if MYSQL_READ_DEFAULT_FILE is set to a non-empty string, then it is interpreted as a path to a , and only that option file is read.

    • if MYSQL_READ_DEFAULT_GROUP is an empty string (or NULL and MYSQL_READ_DEFAULT_FILE is set) then only default groups — [client], [client-server], [client-mariadb] are read.

    • if MYSQL_READ_DEFAULT_GROUP is a non-empty string, then it is interpreted as a custom option group, and that custom option group is read in addition to default groups from above.

    As defined by the proxy protocol specification, a client may prefix its first packet with a proxy protocol header. The server will parse this header and treat the IP address it contains as the client's actual IP address, rather than the address of the connecting process.

    • MARIADB_OPT_PROXY_HEADER: Specifies the proxy protocol header to prefix to the first packet sent to the server. The option requires two additional arguments:

      • a void * pointer to the header buffer, and

      • a size_t value for the buffer length.

    Connection attributes are stored in the and Performance Schema tables. By default, MariaDB Connector/C sends the following connection attributes to the server:

    • _client_name: always "libmariadb"

    • _client_version: version of MariaDB Connector/C

    • _os: operation system

    • _pid: process id

    • _platform: e.g. x86 or x64

    • _server_host: the hostname (as specified in mysql_real_connect). This attribute was added in Connector/C 3.0.5

    • MYSQL_OPT_CONNECT_ATTR_DELETE: Deletes a connection attribute for the given key.

      mysql_optionsv(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, (void *)"app_version");
    • MYSQL_OPT_CONNECT_ATTR_ADD: Adds a key/value pair to connection attributes.

      mysql_optionsv(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, (void *)"app_version", (void *)"2.0.1");
    • MYSQL_OPT_CONNECT_ATTR_RESET: Clears the current list of connection attributes.

      mysql_optionsv(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
    • mysql_init()

    • mysql_options()

    • mysql_real_connect()

    int mysql_optionsv(MYSQL * mysql,
                       enum mysql_option,
                       const void * arg,
                       ...);

    Syntax

    mysql_init()
    mysql_real_connect()
    const char *hdr = "PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n"; mysql_optionsv(mysql, MARIADB_OPT_PROXY_HEADER, (void *)hdr, strlen(hdr));

    Description

    Return Value

    Variable Types

    Options

    Connection Options

    TLS Options

    Plugin Options

    Callback Options

    When a status callback is registered, the connector’s built‑in session tracking functions are disabled. After calling mysql_optionsv() with MARIADB_OPT_STATUS_CALLBACK, the functions mysql_session_track_get_first() and mysql_session_track_get_next() will no longer provide session tracking data. Instead, all session tracking must be managed within the callback itself.

    Replication/Binlog API Options

    Option File Options

    Proxy Settings

    Connection Attribute Options

    If the is disabled, connection attributes will not be stored on server.

    See Also

    spinner
    MYSQL_PROTOCOL_PIPE
  • MYSQL_PROTOCOL_MEMORY.

    enum mysql_protocol_type prot_type= MYSQL_PROTOCOL_SOCKET;
    mysql_optionsv(mysql, MYSQL_OPT_PROTOCOL, (void *)&prot_type);
  • const char *

    MYSQL_INIT_COMMAND, MARIADB_OPT_UNIXSOCKET, MARIADB_OPT_PASSWORD , MARIADB_OPT_USER, MARIADB_OPT_HOST, MARIADB_OPT_SCHEMA, MYSQL_OPT_SSL_KEY, MYSQL_OPT_SSL_CERT, MYSQL_OPT_SSL_CA, MYSQL_OPT_SSL_CAPATH, MYSQL_SET_CHARSET_NAME, MYSQL_SET_CHARSET_DIR, MYSQL_OPT_SSL_CIPHER, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_PLUGIN_DIR, MYSQL_DEFAULT_AUTH, MARIADB_OPT_SSL_FP, MARIADB_OPT_SSL_FP_LIST, MARIADB_OPT_TLS_PASSPHRASE, MARIADB_OPT_TLS_VERSION, MYSQL_OPT_BIND, MYSQL_OPT_CONNECT_ATTR_DELETE, MYSQL_OPT_CONNECT_ATTR_ADD, MARIADB_OPT_CONNECTION_HANDLER, MYSQL_SERVER_PUBLIC_KEY, MARIADB_OPT_RESTRICTED_AUTH

    const char*, unsigned int

    MARIADB_OPT_RPL_REGISTER_REPLICA

    -

    MYSQL_OPT_CONNECT_ATTR_RESET

    void *

    MARIADB_OPT_PROXY_HEADER

    unsigned int timeout= 5;
    mysql_optionsv(mysql, MYSQL_OPT_CONNECT_TIMEOUT, (void *)&timeout);
    static void report_progress(const MYSQL *mysql __attribute__((unused)),
     uint stage, uint max_stage,
     double progress __attribute__((unused)),
     const char *proc_info __attribute__((unused)),
     uint proc_info_length __attribute__((unused)))
    {
     ...
    }
    mysql_optionsv(mysql, MYSQL_PROGRESS_CALLBACK, (void *)report_progress);
    my_bool reconnect= 1; /* enable reconnect */
    mysql_optionsv(mysql, MYSQL_OPT_RECONNECT, (void *)&reconnect);
    unsigned int timeout= 5;
    mysql_optionsv(mysql, MYSQL_OPT_READ_TIMEOUT, (void *)&timeout);
    unsigned int timeout= 5;
    mysql_optionsv(mysql, MYSQL_OPT_WRITE_TIMEOUT, (void *)&timeout);
    mysql_optionsv(mysql, MYSQL_REPORT_DATA_TRUNCATION, NULL); /* disable */
    mysql_optionsv(mysql, MYSQL_REPORT_DATA_TRUNCATION, (void *)"1"); /* enable */
    mysql_optionsv(mysql, MYSQL_SET_CHARSET_DIR, (void *)"/usr/local/mysql/share/mysql/charsets");
    mysql_optionsv(mysql, MYSQL_SET_CHARSET_NAME, (void *)"utf8");
    mysql_optionsv(mysql, MYSQL_OPT_BIND, (void *)"192.168.8.3");
    mysql_optionsv(mysql, MYSQL_OPT_NONBLOCK, 0);
    mysql_optionsv(mysql, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, 1);
    mysql_optionsv(mysql, MYSQL_OPT_MAX_ALLOWED_PACKET, 0x40000000);
    mysql_optionsv(mysql, MYSQL_OPT_NET_BUFFER_LENGTH, 0x40000000);
    mysql_optionsv(mysql, MARIADB_OPT_SCHEMA, (void *)"mydb");
    mysql_optionsv(mysql, MARIADB_OPT_PORT, 3307);
    mysql_optionsv(mysql, MARIADB_OPT_UNIXSOCKET, (void *)"/var/lib/mysql/mysql.sock");
    mysql_optionsv(mysql, MYSQL_OPT_NAMED_PIPE, NULL);
    mysql_optionsv(mysql, MARIADB_OPT_FOUND_ROWS, 1);
    mysql_optionsv(mysql, MYSQL_OPT_COMPRESS, NULL);
    unsigned int enable= 1, disable= 0;
    mysql_optionsv(mysql, MYSQL_OPT_LOCAL_INFILE, (void *)&disable);/* disable */
    mysql_optionsv(mysql, MYSQL_OPT_LOCAL_INFILE, (void *)NULL);     /* enable */
    mysql_optionsv(mysql, MYSQL_OPT_LOCAL_INFILE, (void *)&enable); /* enable */
    mysql_optionsv(mysql, MARIADB_OPT_MULTI_STATEMENTS, (void *)"");
    mysql_optionsv(mysql, MARIADB_OPT_MULTI_RESULTS, 1);
    mysql_optionsv(mysql, MYSQL_SHARED_MEMORY_BASE_NAME, (void *)"mariadb");
    mysql_optionsv(mysql, MYSQL_OPT_SSL_CA, (void *)"certs/ca-cert.pem");
    mysql_optionsv(mysql, MYSQL_OPT_SSL_CAPATH, (void *)"certs/ca-cert.pem");
    mysql_optionsv(mysql, MYSQL_OPT_SSL_CIPHER, (void *)"DHE-RSA-AES256-SHA");
    mysql_optionsv(mysql, MYSQL_OPT_SSL_CAPATH, (void *)"certs/ca-cert.pem");\\\\<<code>>mysql_optionsv(mysql, MYSQL_OPT_SSL_CRL, (void *)"certs/crl.pem");
    mysql_optionsv(mysql, MYSQL_OPT_SSL_CAPATH, (void *)"certs/ca-cert.pem");\\\\<<code>>mysql_optionsv(mysql, MYSQL_OPT_SSL_CRLPATH, (void *)"certs/crls");
    mysql_optionsv(mysql, MARIADB_OPT_SSL_FP, (void *)"3a079e1a14ad326953a5d280f996b93d772a5bea");
    mysql_optionsv(mysql, MARIADB_OPT_TLS_PEER_FP, (void *)"3a079e1a14ad326953a5d280f996b93d772a5bea");
    mysql_optionsv(mysql, MARIADB_OPT_SSL_FP_LIST, (void *)"certs/fingerprints.txt");
    mysql_optionsv(mysql, MARIADB_OPT_TLS_PEER_FP_LIST, (void *)"certs/fingerprints.txt");
    mysql_optionsv(mysql, MARIADB_OPT_SSL_PASSPHRASE, (void *)"thisisashortpassphrase");
    mysql_optionsv(mysql, MARIADB_OPT_TLS_VERSION, (void *)"TLSv1.2,TLSv1.3");
    my_bool verify= 1;
    mysql_optionsv(mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (void *)&verify);
    my_bool enforce_tls= 1;
    mysql_optionsv(mysql, MYSQL_OPT_SSL_ENFORCE, (void *)&enforce_tls);
    unsigned int cipher_strength= 128;
    mysql_optionsv(mysql, MARIADB_OPT_TLS_CIPHER_STRENGTH, (void*)&cipher_strength);
    mysql_optionsv(mysql, MARIADB_OPT_CONNECTION_HANDLER, (void *)"aurora");
    c mysql_optionsv(mysql, MARIADB_OPT_RESTRICTED_AUTH, (void *)"ed25519,caching_sha2_password");
    mysql_optionsv(mysql, MARIADB_OPT_USERDATA, (void *)"ssh_user", (void *)ssh_user);
    my_bool read_only= 1;
    mysql_optionsv(mysql, MARIADB_OPT_CONNECTION_READ_ONLY, (void *)&read_only);
    mysql_optionsv(mysql, MYSQL_PLUGIN_DIR, (void *)"/opt/mariadb/lib/plugins");
    mysql_optionsv(mysql, MYSQL_SECURE_AUTH, 1);
    mysql_optionsv(mysql, MYSQL_SERVER_PUBLIC_KEY, (void *)(void *)"certs/server-cert.pem);

    3rd

    MARIADB_CONST_STRING *

    If track_type is SESSION_TRACK_SYSTEM_VARIABLES: the variable value.

    openssl rehash
    openssl rehash
    custom option file
    Licensing FAQ
    Licensing FAQ

    Configuring MariaDB Connector/C with Option Files

    MariaDB Connector/C reads connection settings from option files such as my.cnf, supporting default and custom file locations, option groups, and a full set of client options.

    Just like MariaDB Server and libmysqlclient, MariaDB Connector/C can also read configuration options from client in .

    Default Option File Locations

    MariaDB Connector/C reads option files from many different directories by default. See the sections below to find out which directories are checked for which system.

    MariaDB Connector/C allows application developers to read options from the default option files by calling the mysql_optionsv function and providing the MYSQL_READ_DEFAULT_FILE option name and a NULL pointer as arguments. For example:

    mysql_optionsv(mysql, MYSQL_READ_DEFAULT_FILE, NULL);

    MYSQL_READ_DEFAULT_FILE is exclusive: if the application calls it more than once, the second call replaces the value set by the first. To read both a custom option file and the default option files, pass the custom file path in a single call; reading default files is controlled separately via MYSQL_READ_DEFAULT_GROUP.

    Default Option File Locations on Linux, Unix, Mac

    On Linux, Unix, or Mac OS X, the default option file is called my.cnf. MariaDB Connector/C looks for the MariaDB option file in the locations and orders listed below.

    The locations are dependent on whether the DEFAULT_SYSCONFDIR option was defined when MariaDB Connector/C was built. This option is usually defined as /etc when building , but it is usually not defined when building or .

    • When the DEFAULT_SYSCONFDIR option was not defined, MariaDB Connector/C looks for the MariaDB option file in the following locations in the following order:

    Location
    • When the DEFAULT_SYSCONFDIR option was defined, MariaDB Connector/C looks for the MariaDB option file in the following locations in the following order:

    Location

    On Windows, the default option file can be called either my.ini or my.cnf. MariaDB Connector/C looks for the MariaDB option file in the following locations in the following order:

    Location
    • The System Windows Directory is the directory returned by the function. The value is usually C:\Windows. To find its specific value on your system, open and execute:

    • The Windows Directory is the directory returned by the function. The value may be a private Windows Directory for the application, or it may be the same as the System Windows Directory returned by the function.

    • EXEDIR is the parent directory of the executable program that MariaDB Connector/C is linked with.

    MariaDB Connector/C will look in all of the above locations, in order, even if has already found an option file, and it's possible for more than one option file to exist. For example, you could have an option file in /etc/my.cnf with global settings for all servers, and then you could another option file in ~/.my.cnf (i.e.your user account's home directory) which will specify additional settings (or override previously specified setting) that are specific only to that user.

    MariaDB Connector/C allows application developers to read option files from a custom option file by calling the function and providing the option name and an option file path as arguments. For example:

    Many MariaDB clients can be configured to read options from custom options files with the following command-line arguments. They must be given as the first argument on the command-line. Application developers who use MariaDB Connector/C in their application and rely on option files may also want to consider implementing these command-line arguments:

    Option
    Description

    The command-line option is roughly equivalent to setting the option with a non-NULL argument.

    The command-line option does not yet have an equivalent option in MariaDB Connector/C. See for more information.

    The syntax of the MariaDB option files are:

    • Lines starting with

    • Empty lines are ignored.

    • Option groups use the syntax [group-name]. See the section below for more information on available option groups.

    MariaDB Connector/C reads client options from the following in :

    Group
    Description

    MariaDB Connector/C allows application developers to read options from these option groups by calling the function and providing the option name and a NULL pointer as arguments.

    For example:

    MariaDB Connector/C allows application developers to read options from a custom option group by calling the function and providing the option name and the name of the custom option group as arguments.

    For example:

    The custom option group will be read in addition to the default option groups listed above.

    Many MariaDB clients can be configured to read options from option groups with a custom suffix by providing the following command-line argument. It must be given as the first argument on the command-line. Application developers who use MariaDB Connector/C in their application and rely on option files may also want to consider implementing this command-line argument:

    Option
    Description

    The command-line option does not yet have an equivalent option in MariaDB Connector/C. See for more information.

    It is possible to include additional option files from another option file. For example, to include /etc/mysql/dbserver1.cnf, an option file could contain:

    It is also possible to include the default option files in a directory from another option file. For example, to include the default option files in /etc/my.cnf.d/, an option file could contain:

    Unlike with MariaDB server, this directive does not configure MariaDB Connector/C to include all option files ending in .cnf on Unix-like operating systems or all option files ending in .cnf and .ini files on Windows. Instead, it just configures MariaDB Connector/C to include the my.cnf in the given directory, and also the my.ini in the given directory if it's Windows. See for more information.

    For many MariaDB clients, you can check which options a given program is going to use by using the command-line argument:

    Option
    Description

    It must be given as the first argument on the command-line. Application developers who use MariaDB Connector/C in their application and rely on option files may also want to consider implementing this command-line argument. For example:

    If it is installed on your system, then you can also check which options a given program is going to use by using the utility and providing the names of the option groups that the program reads.

    For example:

    See for more information.

    MySQL 5.6 and above support an obfuscated authentication credential option file called .mylogin.cnf that is created with .

    MariaDB Connector/C does not support this. The passwords in MySQL's .mylogin.cnf are only obfuscated, rather than encrypted, so the feature does not really add much from a security perspective. It is more likely to give users a false sense of security, rather than to seriously protect them.

    MariaDB Connector/C options can be set in client .

    Underscores (_) in option names are treated the same as dashes (-) for MariaDB Connector/C. See for more information.

    Unlike with the server, the loose prefix has no meaning for MariaDB Connector/C. Unknown options will simply be ignored.

    MariaDB Connector/C allows application developers to implement custom options in option files by defining a function that matches this signature:

    And then assigning the function pointer to mysql->options.extension->set_option.

    These are the options supported in option files by MariaDB Connector/C by default.

    These options can also be set inside your application with the function.

    bind-address

    • Description: Specify the network interface from which to connect to MariaDB Server.

    • mysql_optionsv: MYSQL_OPT_BIND

    • Data Type: string

    character-sets-dir

    • Description: Directory for files.

    • mysql_optionsv: MYSQL_SET_CHARSET_DIR

    • Data Type: string

    compress

    • Description: Compress all information sent between the client and the server if both support compression.

    • mysql_optionsv: MYSQL_OPT_COMPRESS

    • Data Type: boolean

    connect-timeout, timeout

    • Description: Connect timeout in seconds. This value will be passed as an unsigned int parameter.

    • mysql_optionsv: MYSQL_OPT_CONNECT_TIMEOUT

    • Data Type: int

    database

    • Description: Database to use.

    • mysql_optionsv: MARIADB_OPT_SCHEMA

    • Data Type: string

    debug

    • Description:

    • mysql_optionsv: MARIADB_OPT_DEBUG

    • Data Type: string

    default-auth

    • Description: Default authentication client-side plugin to use.

    • mysql_optionsv: MYSQL_DEFAULT_AUTH

    • Data Type: string

    default-character-set

    • Description: Specify the default for the connection.

    • mysql_optionsv: MYSQL_SET_CHARSET_NAME

    • Data Type: string

    disable-local-infile

    • Description: Disable the use of .

    • mysql_optionsv: N/A

    • Data Type: string

    host

    • Description: Hostname or IP address of the server to connect to.

    • mysql_optionsv: MARIADB_OPT_HOST

    • Data Type: string

    interactive-timeout

    • Description:

    • mysql_optionsv: MARIADB_OPT_INTERACTIVE

    • Data Type: none

    init-command

    • Description: Command(s) which will be executed when connecting and reconnecting to the server.

    • mysql_optionsv: MYSQL_INIT_COMMAND

    • Data Type: string

    local-infile

    • Description: Enable or disable the use of .

    • mysql_optionsv: MYSQL_OPT_LOCAL_INFILE

    • Data Type: boolean

    max-allowed-packet

    • Description: The maximum packet length to send to or receive from server. The default is 16MB, the maximum 1GB.

    • mysql_optionsv: MYSQL_OPT_MAX_ALLOWED_PACKET

    • Data Type: size_t

    multi-results

    • Description: Indicates that the client is able to handle multiple result sets from stored procedures or multi statements. This option will be automatically set if multi-statements is set.

    • mysql_optionsv: MARIADB_OPT_MULTI_RESULTS

    • Data Type: boolean

    multi-statements, multi-queries

    • Description: Allows the client to send multiple statements in one command. Statements will be divided by a semicolon.

    • mysql_optionsv: MARIADB_OPT_MULTI_STATEMENTS

    • Data Type: boolean

    net-buffer-length

    • Description: The buffer size for TCP/IP and socket communication. Default is 16KB.

    • mysql_optionsv: MYSQL_OPT_NET_BUFFER_LENGTH

    • Data Type: size_t

    password

    • Description: Password of the user to login to the server.

    • mysql_optionsv: MARIADB_OPT_PASSWORD

    • Data Type: string

    pipe

    • Description: For Windows operating systems only: Use named pipes for client/server communication.

    • mysql_optionsv: MYSQL_OPT_NAMED_PIPE

    • Data Type: boolean

    plugin-dir

    • Description: Specify the location of client plugins.

      • The plugin directory can also be specified with the MARIADB_PLUGIN_DIR environment variable.

    • mysql_optionsv: MYSQL_PLUGIN_DIR

    port

    • Description: Port number to use for connection.

    • mysql_optionsv: MARIADB_OPT_PORT

    • Data Type: int

    protocol

    • Description: Specify the type of client/server protocol. Possible values are:

      • 0 - Refers to MYSQL_PROTOCOL_DEFAULT

      • 1 - Refers to MYSQL_PROTOCOL_TCP

    reconnect

    • Description: Enable or disable automatic reconnect.

    • mysql_optionsv: MYSQL_OPT_RECONNECT

    • Data Type: boolean

    report-data-truncation

    • Description: Enable or disable reporting data truncation errors for prepared statements.

    • mysql_optionsv: MYSQL_REPORT_DATA_TRUNCATION

    • Data Type: boolean

    return-found-rows

    • Description: Return the number of matched rows instead of number of changed rows.

    • mysql_optionsv: MARIADB_OPT_FOUND_ROWS

    • Data Type: none

    secure-auth

    • Description: Refuse client connecting to server if it uses old (pre-MySQL4.1.1) protocol. Defaults to false (unlike MySQL since 5,6, which defaults to true).

    • mysql_optionsv: MYSQL_SECURE_AUTH

    • Data Type: boolean

    server_public_key

    • Description: Specifies 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 client authentication plugin.

    • mysql_optionsv: MYSQL_SERVER_PUBLIC_KEY

    • Data Type: string

    shared-memory-base-name

    • Description: Shared-memory name to use for Windows connections using shared memory to a local server (started with the --shared-memory option). Case-sensitive.

    • mysql_optionsv: MYSQL_SHARED_MEMORY_BASE_NAME

    • Data Type: string

    socket

    • Description: For connections to localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.

    • mysql_optionsv: MARIADB_OPT_UNIXSOCKET

    • Data Type: string

    ssl-ca

    • Description: Defines a path to a PEM file that should contain one or more X509 certificates for trusted Certificate Authorities (CAs) to use for . This option requires that you use the absolute path, not a relative path.

      • See for more information.

    • mysql_optionsv: MYSQL_OPT_SSL_CA

    ssl-capath

    • Description: Defines 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 for . This option requires that you use the absolute path, not a relative path. The directory specified by this option needs to be run through the command.

      • See for more information.

      • This option is only supported if the connector was built with OpenSSL. If the connector was built with GnuTLS or Schannel, then this option is not supported. See for more information about which libraries are used on which platforms.

    ssl-cert

    • Description: Defines a path to the X509 certificate file to use for . This option requires that you use the absolute path, not a relative path.

    • mysql_optionsv: MYSQL_OPT_SSL_CERT

    • Data Type: string

    ssl-cipher

    • Description: List of permitted ciphers or cipher suites to use for .

    • mysql_optionsv: MYSQL_OPT_SSL_CIPHER

    • Data Type: string

    ssl-crl

    • Description: Defines a path to a PEM file that should contain one or more revoked X509 certificates to use for . This option requires that you use the absolute path, not a relative path.

      • See for more information.

      • This option is only supported if the connector was built with OpenSSL or Schannel. If the connector was built with GnuTLS, then this option is not supported. See for more information about which libraries are used on which platforms.

    ssl-crlpath

    • Description: Defines a path to a directory that contains one or more PEM files that should each contain one revoked X509 certificate to use for . This option requires that you use the absolute path, not a relative path. The directory specified by this option needs to be run through the command.

      • See for more information.

      • This option is only supported if the connector was built with OpenSSL. If the connector was built with GnuTLS or Schannel, then this option is not supported. See for more information about which libraries are used on which platforms.

    ssl-enforce

    • Description: Whether to force .

    • mysql_optionsv: MYSQL_OPT_SSL_ENFORCE

    • Data Type: boolean

    ssl-fp

    • Description: Description: Specify the fingerprint hash of a server certificate for validation during the handshake. handshake. In Connector/C versions prior to 3.4.0, only SHA1 hashes are accepted. From version 3.4.0 onward, SHA256, SHA384, and SHA512 hashes are also supported.

    • mysql_optionsv: MARIADB_OPT_SSL_FP

    ssl-fp-list, ssl-fplist

    • Description: Description: Specify a file which contains one or more fingerprint hashes of server certificates for validation during the handshake. In Connector/C versions prior to 3.4.0, only SHA1 hashes are accepted. From version 3.4.0 onward, SHA256, SHA384, and SHA512 hashes are also supported.

    • mysql_optionsv: MARIADB_OPT_SSL_FP_LIST

    ssl-key

    • Description: Defines a path to a private key file to use for . This option requires that you use the absolute path, not a relative path. If the key is protected with a passphrase, the passphrase needs to be specified with ssl-passphrase option.

    • mysql_optionsv: MYSQL_OPT_SSL_KEY

    • Data Type: string

    ssl-passphrase

    • Description: Specify a passphrase for a passphrase-protected private key, as configured by the option.

      • This option is only supported if the connector was built with OpenSSL or GnuTLS. If the connector was built with Schannel, then this option is not supported. See for more information about which libraries are used on which platforms.

    • mysql_optionsv: MARIADB_OPT_TLS_PASSPHRASE

    ssl-verify-server-cert

    • Description: Enables (or disables) .

    • mysql_optionsv: MYSQL_OPT_SSL_VERIFY_SERVER_CERT

    • Data Type: boolean

    tls_version

    • Description: Defines which protocol versions are allowed. This should be a comma-separated list of TLS protocol versions to allow. Valid TLS protocol versions are TLSv1.0, TLSv1.1, TLSv1.2, and TLSv1.3. Both the client and server should support the allowed TLS protocol versions. See for information on which TLS libraries support which TLS protocol versions. See for more information about which TLS libraries are used on which platforms.

    • mysql_optionsv: MARIADB_OPT_TLS_VERSION

    user

    • Description: User to login to the server.

    • mysql_optionsv: MARIADB_OPT_USER

    • Data Type: string

    EXEDIR\my.ini

    EXEDIR\my.cnf

    %MYSQL_HOME%\my.ini

    %MYSQL_HOME%\my.cnf

    MYSQL_HOME is the containing the path to the directory holding the server-specific my.cnf file.

    The same option group can appear multiple times.
  • The !include directive can be used to include other option files. See the Including Option Files section below for more information on this syntax.

  • Unlike with the server, the !includedir directive does not include all .cnf files (and potentially .ini files) in a given directory. Instead, it reads the my.cnf and (potentially the my.ini) in the given directory. See CONC-396 for more information. See the Including Option File Directories section below for more information on this syntax.

  • Dashes (-) and underscores (_) in options are interchangeable in MariaDB Connector C 3.1.1 and later. In versions before that, options must be specified exactly as they are defined. See CONC-395 for more information.

  • MariaDB Connector/C does not support the that are supported by MariaDB Server. See CONC-415 for more information.

  • See the Options section below for information about available options.

  • Default Value:

  • Introduced: MariaDB Connector/C 3.0.0

  • Default Value:

    Default Value: false

    Default Value:

    Default Value:
    Default Value:

    Default Value:

    Default Value:

    Default Value:

    Default Value:

    Default Value:

    Default Value:

    Default Value: false

    Default Value:

    Default Value:

    Default Value:

    Default Value:

  • Introduced: MariaDB Connector/C 3.0.0

  • Default Value:

    Default Value: false

    Data Type: string

  • Default Value:

  • Default Value: 3306

  • 2 - Refers to MYSQL_PROTOCOL_SOCKET

  • 3 - Refers to MYSQL_PROTOCOL_PIPE

  • 4 - Refers to MYSQL_PROTOCOL_MEMORY

  • mysql_optionsv: MYSQL_OPT_PROTOCOL

  • Data Type: int

  • Default Value:

  • Default Value: false

  • Introduced: MariaDB Connector/C 3.0.0

  • Default Value:

    Default Value:

    Default Value: false

    Default Value:

  • Introduced: MariaDB Connector/C 3.1.0

  • Default Value:

    Default Value:

    Data Type: string

  • Default Value:

  • mysql_optionsv: MYSQL_OPT_SSL_CAPATH

  • Data Type: string

  • Default Value:

  • Default Value:

    Default Value:

    mysql_optionsv: MYSQL_OPT_SSL_CRL

  • Data Type: string

  • Default Value:

  • Introduced: MariaDB Connector/C 3.1.1

  • mysql_optionsv: MYSQL_OPT_SSL_CRLPATH

  • Data Type: string

  • Default Value:

  • Introduced: MariaDB Connector/C 3.1.1

  • Default Value:

  • Introduced: MariaDB Connector/C 3.1.1

  • Data Type: string

  • Default Value:

  • Introduced: MariaDB Connector/C 3.0.0

  • Data Type: string

  • Default Value:

  • Introduced: MariaDB Connector/C 3.0.0

  • Default Value:

  • Data Type: string

  • Default Value:

  • Introduced: MariaDB Connector/C 3.0.0

  • Default Value:

  • Introduced: MariaDB Connector/C 3.0.0

  • Data Type: string

  • Default Value:

  • Introduced: MariaDB Connector/C 3.0.4

  • Default Value:

    /etc/my.cnf

    /etc/mysql/my.cnf

    $MYSQL_HOME/my.cnf

    ~/.my.cnf

    DEFAULT_SYSCONFDIR/my.cnf

    $MYSQL_HOME/my.cnf

    ~/.my.cnf

    System Windows Directory\my.ini

    System Windows Directory\my.cnf

    Windows Directory\my.ini

    Windows Directory\my.cnf

    C:\my.ini

    echo %WINDIR%
    mysql_optionsv(mysql, MYSQL_READ_DEFAULT_FILE, (void *)"./my_conf.cnf");

    =path

    Only read options from the given option file.

    =path

    Read this extra option file after all other option files are read.

    [client]

    Options read by all MariaDB and MySQL client programs, which includes both MariaDB and MySQL clients. For example, mysqldump.

    [client-server]

    Options read by all MariaDB client programs and the MariaDB Server. This is useful for options like socket and port, which is common between the server and the clients.

    [client-mariadb]

    Options read by all MariaDB client programs.

    mysql_optionsv(mysql, MYSQL_READ_DEFAULT_GROUP, NULL);
    mysql_optionsv(mysql, MYSQL_READ_DEFAULT_GROUP, (void *)"my_section");

    =suffix

    In addition to the default option groups, also read option groups with the given suffix.

    [client-mariadb]
    ...
    !include /etc/mysql/dbserver1.cnf
    [client-mariadb]
    ...
    !includedir /etc/my.cnf.d/

    Read options from option files, print all option values, and then exit the program.

    mysqldump --print-defaults
    mysqldump would have been started with the following arguments:
    --ssl_cert=/etc/my.cnf.d/certificates/client-cert.pem --ssl_key=/etc/my.cnf.d/certificates/client-key.pem --ssl_ca=/etc/my.cnf.d/certificates/ca.pem --ssl-verify-server-cert --max_allowed_packet=1GB
    my_print_defaults my_section client client-server client-mariadb
    --ssl_cert=/etc/my.cnf.d/certificates/client-cert.pem
    --ssl_key=/etc/my.cnf.d/certificates/client-key.pem
    --ssl_ca=/etc/my.cnf.d/certificates/ca.pem
    --ssl-verify-server-cert
    --max_allowed_packet=1073741824
    my_bool (*set_option)(MYSQL *mysql, const char *config_option, const char *config_value);

    Environment variable precedence: If the $MARIADB_HOME environment variable is set, MariaDB Connector/C reads $MARIADB_HOME/my.cnf and ignores $MYSQL_HOME entirely. Only if $MARIADB_HOME is not set will the connector fall back to $MYSQL_HOME/my.cnf. If neither variable is set, this location is skipped.

    $HOME and the ~/.my.cnf path: If $HOME is unset in the shell environment, the connector will not locate ~/.my.cnf and will silently skip it without returning an error.

    Default Option File Locations on Windows

    Environment variable precedence: If the %MARIADB_HOME% environment variable is set, MariaDB Connector/C reads %MARIADB_HOME%\my.ini (or %MARIADB_HOME%\my.cnf) and ignores %MYSQL_HOME% entirely. Only if %MARIADB_HOME% is not set will the connector fall back to %MYSQL_HOME%.

    Default Option File Hierarchy

    Custom Option File Locations

    Option File Syntax

    Option Groups

    Custom Option Groups

    MYSQL_READ_DEFAULT_GROUP is an exclusive option: calling it more than once replaces the previously specified custom group name. Only one non‑default group can be defined in this way. Options are applied in the order their [group] sections appear in the option file, with a later section's values overriding earlier ones — the custom group does not have inherent precedence over the built‑in default groups ([client], [client-server], [client-mariadb]); its effect depends on where its section appears relative to theirs. Passing an empty string causes only the default groups to be read, with no custom group applied:

    mysql_optionsv(mysql, MYSQL_READ_DEFAULT_GROUP, (void *)"");

    MySQL compatibility note: MySQL Connector/C recognizes only [client] as a default group. To ensure option files work with both connectors, place shared settings in [client] and MariaDB‑specific settings in [client-mariadb]. A MySQL connector ignores [client-mariadb], while a MariaDB connector reads [client] first and then applies overrides from [client-mariadb].

    Including Option Files

    Including Option File Directories

    Checking Program Options

    Numeric suffixes such as K, M, or G are not supported in option file values. The connector reads only the numeric portion and silently discards any trailing non‑numeric characters. Always specify byte counts as plain integer values in option files.

    MySQL 5.6 Obfuscated Authentication Credential Option File

    Options

    Custom Options

    Default Options

    Unlike most options, init-command is a multi-element option. Each occurrence in an option file appends the statement to an internal list rather than replacing the previous value. If init-command is specified in both /etc/my.cnf and ~/.my.cnf, all statements will execute on each connect and reconnect, in an unspecified order. Remember to use this option with caution, especially when multiple option files are in use, as statements defined in system‑wide files may not be visible when editing user‑level files.

    See Also

    cmake
    cmake
    cmake
    GetSystemWindowsDirectory
    cmd.exe
    GetWindowsDirectory
    GetSystemWindowsDirectory
    mysql_optionsv
    MYSQL_READ_DEFAULT_FILE
    MYSQL_READ_DEFAULT_FILE
    CONC-399
    Option Groups
    mysql_optionsv
    MYSQL_READ_DEFAULT_GROUP
    mysql_optionsv
    MYSQL_READ_DEFAULT_GROUP
    CONC-404
    CONC-396
    mysql_config_editor
    option groups
    CONC-395
    mysql_optionsv
    openssl rehash
    openssl rehash
    ssl-key
    spinner

    C:\my.cnf

    MariaDB Connector/C 3.1.0
    MariaDB Connector/C 3.1.0
    MariaDB Connector/C 3.1.0
    MariaDB Connector/C 3.1.0
    MariaDB Connector/C 3.1.0
    MariaDB Connector/C 3.1.0
    MariaDB Connector/C 3.1.0
    MariaDB 10.2
    3.4.9
    character set
    TLS connection
    error code
    AUTO_INCREMENT
    LAST_INSERT_ID(expr)
    INSERT
    UPDATE
    AUTO_INCREMENT
    LAST_INSERT_ID
    AUTO INCREMENT
    LAST_INSERT_ID()
    error log
    autocommit
    INSERT
    UPDATE
    DELETE
    REPLACE
    UPDATE
    REPLACE
    character set
    SHOW PROCESSLIST
    KILL QUERY
    autocommit
    Autocommit
    --debug
    MariaDB Package Repository setup script
    INSERT INTO...SELECT...
    INSERT INTO...VALUES (...),(...),(...)
    LOAD DATA INFILE ...
    SELECT ...
    ALTER TABLE ...
    UPDATE ...
    MSI packages
    binary tarballs
    MariaDB Package Repository setup script
    RPM package
    yum
    dnf
    DEB package
    RPM package
    zypper
    option groups
    option files
    mariadb_es_repo_setup
    mariadb_repo_setup
    Versions
    MariaDB Package Repository Setup and Usage
    mariadb_es_repo_setup
    Versions
    MariaDB Package Repository Setup and Usage
    mariadb_repo_setup
    --mariadb-server-version
    --mariadb-server-version
    mariadb_es_repo_setup
    mariadb_repo_setup
    TLS
    TLS
    mysql_clear_password
    session_connect_attrs
    session_account_connect_attrs
    LOAD DATA LOCAL INFILE
    ALTER TABLE
    character set
    character set
    LOAD DATA LOCAL INFILE
    TLS
    Secure Connections Overview: Certificate Authorities (CAs)
    TLS
    Secure Connections Overview: Certificate Authorities (CAs)
    TLS and Cryptography Libraries Used by MariaDB
    TLS
    TLS
    Secure Connections Overview: Certificate Revocation Lists (CRLs)
    TLS and Cryptography Libraries Used by MariaDB
    TLS
    Secure Connections Overview: Certificate Revocation Lists (CRLs)
    TLS and Cryptography Libraries Used by MariaDB
    TLS
    TLS
    TLS
    TLS
    TLS and Cryptography Libraries Used by MariaDB
    TLS
    Secure Connections Overview: TLS Protocol Version Support
    TLS and Cryptography Libraries Used by MariaDB
    server certificate verification
    TLS
    mysql_old_password
    caching_sha2_password
    Performance Schema
    option groups
    option files
    RPM packages
    DEB packages
    binary tarballs
    --
    defaults-file
    --
    defaults-extra-file
    option groups
    option files
    --
    defaults-group-suffix
    --
    print-defaults
    my_print_defaults
    Configuring MariaDB with Option Files: Checking Program Options
    character set
    character set
    LOAD DATA LOCAL INFILE
    LOAD DATA LOCAL INFILE
    caching_sha2_password
    TLS
    Secure Connections Overview: Certificate Authorities (CAs)
    TLS
    Secure Connections Overview: Certificate Authorities (CAs)
    TLS and Cryptography Libraries Used by MariaDB
    TLS
    TLS
    TLS
    Secure Connections Overview: Certificate Revocation Lists (CRLs)
    TLS and Cryptography Libraries Used by MariaDB
    TLS
    Secure Connections Overview: Certificate Revocation Lists (CRLs)
    TLS and Cryptography Libraries Used by MariaDB
    TLS
    TLS
    TLS
    TLS
    TLS and Cryptography Libraries Used by MariaDB
    server certificate verification
    TLS
    Secure Connections Overview: TLS Protocol Version Support
    TLS and Cryptography Libraries Used by MariaDB
    Configuring MariaDB with Option Files
    environment variable
    option prefixes
    --defaults-file
    --defaults-extra-file
    --defaults-group-suffix
    --print-defaults