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)
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.
#include <mysql.h>
unsigned long mysql_net_field_length(unsigned char **packet)
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.
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.
attr: A pointer which returns extended metadata information
field: Specifies the field which contains extended metadata information
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.
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.
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.
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.
mysql_change_user changes the authenticated user and default database on an existing connection, resetting session state including transactions, temporary tables, and locks.
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 function.
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.
Returns zero on success, nonzero if an error occurred.
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.
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.
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.
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.
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.
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);
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.
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 function or obtained by function.
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().
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.
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);
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 or after retrieving all rows in the result.
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.
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.
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.
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().
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.
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.
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
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.
#include <mysql.h>
unsigned int mysql_get_timeout_value_ms(const MYSQL *mysql);
Parameter
Parameter
Description
mysql
A connection handle previously allocated by and connected by .
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.
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.
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.
The mysql_init() function returns an address of a MYSQL structure, or NULL in case of memory allocation error.
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.
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.
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.
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 should be used.
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_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.
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 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.
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.
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.
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.
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);
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).
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.
mysql - a mysql handle, which was previously allocated by or .
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.
Returns zero on success, nonzero if an error occurred.
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);
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.
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.
Optional arguments passed to the plugin's initialization function.
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
MARIADB_CLIENT_CONNECTION_PLUGIN or MARIADB_CLIENT_COMPRESSION_PLUGIN.
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.
The directory which contains the plugin can be specified either by the environment variable MARIADB_PLUGIN_DIR or it can be specified with using the option MYSQL_PLUGIN_DIR.
See Also
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_get_info().
mariadb_field_attr was added in MariaDB Connector/C 3.1.8.
If a reconnect occurred the thread_id will change. Also resources bundled to the connection (prepared statements, locks, temporary tables, ...) will be released.
# 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;
}
Return Value
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
Description
Return Value
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.
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.
mysql - a mysql handle, which was previously allocated by or . 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.
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.
debug - a string representing the debug operation to perform. See description below.
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).
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.
mysql - a mysql handle, which was previously allocated by or .
mysql_option - the option you want to retrieve. See description below.
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.
MYSQL RES * - A result set identifier returned by or .
Returns number of fields in a specified result set.
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_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_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.
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 of the connected MariaDB server.Parameter type: unsigned long.
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 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 . This option was added in version 3.4.1
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,
/* 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);
Description
Value types
Generic information
Connection related information
Return Value
History
Examples
See Also
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
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
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 mysql_optionsv.
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_NONBLOCK
MYSQL_OPT_SSL_VERIFY_SERVER_CERT
MARIADB_OPT_CONNECTION_READ_ONLY
MYSQL_SECURE_AUTH
MYSQL_OPT_CONNECT_TIMEOUT
MYSQL_OPT_READ_TIMEOUT
MYSQL_OPT_WRITE_TIMEOUT
MYSQL_OPT_LOCAL_INFILE
MYSQL_OPT_PROTOCOL
MYSQL_INIT_COMMAND
char **commands;
int elements;
rc = mysql_get_optionv(mysql, MYSQL_INIT_COMMAND, &commands, &elements);
MYSQL_READ_DEFAULT_FILE
MYSQL_READ_DEFAULT_GROUP
MYSQL_SET_CHARSET_NAME
MYSQL_PLUGIN_DIR
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
MYSQL_PROGRESS_CALLBACK: requires a function pointer *(const MYSQL *, uint, uint, double, const char *, uint))arg)
MYSQL_CONNECT_ATTRS: this option requires 5 parameters:
/* 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]);
MARIADB_OPT_USERDATA: retrieves userdata for a given key.
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.
Returns the number of warnings from the last executed query, or zero if there are no warnings.
For retrieving warning messages you should use the SQL command . If TRADITIONAL is enabled an error instead of warning will be returned. For detailed information check the server documentation.
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
mysql_real_escape_string
mysql_real_escape_string encodes a string for safe use in a SQL statement, taking the connection's current character set into account when escaping special characters.
mysql - a MySQL handle, which was previously allocated by or .
to - buffer for the encoded string. The size of this buffer must be length * 2 + 1 bytes: in the worst case every character of the from string needs to be escaped. Additionally, a trailing 0 character will be appended.
mysql_reset_connection
mysql_reset_connection resets session state on a MariaDB Connector/C connection — rolling back transactions and clearing variables — without disconnecting or reauthenticating.
mysql - a MySQL handle, which was previously allocated by or .
Resets the current connection and clears session state. Similar to or , mysql_reset_connection() resets session status, but without disconnecting, opening, or reauthenticating.
On client side mysql_reset_connection()
mysql_refresh
mysql_refresh flushes server-side caches and state using a bitmask of options such as REFRESH_GRANT, REFRESH_LOG, REFRESH_TABLES, and REFRESH_HOSTS.
mysql - a mysql handle, which was previously allocated by or .
options - a bit masked composed integer. See below.
Flushes different types of information stored on the server. The bit-masked parameter options specify which kind of information will be flushed.
mysql_row_seek
mysql_row_seek repositions the row cursor in a buffered MariaDB result set to an arbitrary offset, returning the previous row position as a MYSQL_ROW_OFFSET.
result - a result set identifier returned by .
offset - row offset. This value can be obtained either by mysql_row_seek() or
mysql_shutdown
mysql_shutdown sends a shutdown request to the MariaDB server over the current connection, requiring the SHUTDOWN privilege for the authenticated user.
mysql - a mysql handle, which was previously allocated by or .
mysql_enum_shutdown_level - currently only one shutdown level, SHUTDOWN_DEFAULT is supported.
mysql_thread_safe
mysql_thread_safe returns 1 if the MariaDB Connector/C client library was compiled with thread-safety support, or zero otherwise.
Indicates whether or not the client library is compiled as thread safe. Returns 1 if the client library was compiled as thread safe otherwise zero.
Returns always 1.
mysql_thread_end
mysql_thread_end 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.
The mysql_thread_end() function is now an empty no-op, retained only for API/ABI compatibility.
Returns void.
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.
Immediately aborts a connection by making all subsequent read/write operations fail, without freeing the MYSQL structure or closing communication channels.
Function Overview
from - a string which will be encoded by mysql_real_escape_string().
long - the length of the from string.
This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection.
Unlike mysql_thread_init()mysql_thread_end() will not be invoked automatically if the thread ends. To avoid memory leaks mysql_thread_end() must be called explicitly.
This function has been deprecated since MariaDB Connector/C 3.0.0.
Returns a string containing the error code for the most recently invoked function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.
Please note that not all client library error codes are mapped to SQLSTATE errors. Errors which can't be mapped will be returned as value HY000.
mysql_set_local_infile_handler registers custom callback functions for init, read, end, and error phases of a LOAD DATA LOCAL INFILE operation in MariaDB Connector/C.
Name
mysql_set_local_infile_handler - Registers callback functions for LOAD DATA LOCAL INFILE
Registers four callback functions which will be called if a LOAD DATA LOCAL INFILE command will be executed.
The initialization function accepts 3 parameters and returns zero on success, nonzero on error. It allocates an handle, which will be passed to read, end and error functions:
int init(void **handle, const char *filename, void *userdata)
The read function is called repeatedly to read data chunks from file into buffer. The amount of bytes is limited by parameer buffer_len. The function returns the number of bytes which were read from the file:
int mysql_local_infile_read(void *handle, char * buffer, unsigned int buffer_len)
The end function will be called after the read function returned zero (no more bytes to read). To prevent leaking of resources, the file must be closed and handle must be freed inside this function:
void end(void *handle);
The error function is called to get an error message in case init, read or end functions returned an error.
error(void *handler, char *error_buf, unsigned int error_buf_len);
mysql - mysql handle, which was previously allocated by
local_infile_init - initialization function, e.g. for opening the file
mysql_set_local_infile_default resets local infile callbacks to the Connector/C internal defaults, reversing any custom handler registered via mysql_set_local_infile_handler.
Name
mysql_set_local_infile_default - Sets local infile callback functions to default
mysql_row_tell 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.
res - a result set identifier returned by .
Returns the row offset of a result cursor. The returned offset value can be used to reposition the result cursor by calling .
local_infile_end - terminating function, e.g. for closing the file
local_infile_error - error function
userdata - a buffer which will be passed to all callback function
Reset master server information and restart slaves.
REFRESH_MASTER
Remove binary log files.
# switch to default database test
USE test;
# check default database
SELECT DATABASE();
+------------+
| database() |
+------------+
| test |
+------------+
static int set_default_db(MYSQL *mysql)
{
int rc;
char *default_db;
/* change default database to test */
rc= mysql_select_db(mysql, "test");
if (rc)
return rc; /* Error */
/* get the default database */
rc= mariadb_get_infov(mysql, MARIADB_CONNECTION_SCHEMA, &default_db);
if (rc)
return rc; /* Error */
if (strcmp("test", default_db) != NULL)
{
printf("Wrong default database\n");
return 1;
}
printf("Default database: %s", default_db);
return 0;
}
To retrieve the name of the default database either execute the SQL command SELECT DATABASE() or retrieve the value via mariadb_get_infov() API function.
The default database can also be set by the db parameter in mysql_real_connect().
mysql_send_query dispatches a query asynchronously on a MariaDB connection; each call must be followed by mysql_read_query_result to consume the response.
Syntax
int mysql_send_query(MYSQL * mysql,
const char * query,
unsigned long length);
mysql_send_query() executes a SQL statement without waiting for the Server OK packet and/or resultset. The main purpose of this function is to perform batch execution of DML statements.
For an example how to use 'mysql_send_query()` in an event driven model, please check Jan Kneschke's article .
mysql_read_query_result reads the result of a statement previously sent with mysql_send_query, and must be called once for each successful mysql_send_query call.
mysql_read_query_result() reads the result of a SQL statement executed with mysql_send_query(). If the SQL statement returned a result set, it must be freed before the next call to mysql_read_query_result() is made. This is similar to how results from mysql_query() must be processed before another call can be made.
Return Value
Returns zero on success, otherwise non-zero.
For an example how to use in an event driven model, please check Jan Kneschke's Blog entry .
mysql_ssl_set configures TLS parameters including key, certificate, CA, and cipher list for a MariaDB connection, and must be called before mysql_real_connect.
mysql - a mysql handle, which was previously allocated by or .
key - path to the key file.
mysql_thread_init
mysql_thread_init 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.
Thread initialization for multi-threaded clients. mysql_thread_init() is now an empty no-op; it is not called automatically by or .
Always returns 0 (no-op).
Description
The OK and result set package need to be retrieved by mysql_read_query_result() function
mysql_send_query() can be used for semi asynchronous operation. While the function itself is blocking, an event driven application can do other tasks until result set is available.
capath - path to the directory containing the trusted TLS CA certificates in PEM format.
cipher list of permitted ciphers to use for TLS encryption.
Used for establishing a . It must be called before attempting to use mysql_real_connect(). TLS support must be enabled in the client library in order for the function to have any effect.
NULL can be used for an unused parameter. Always returns zero.
To enable TLS without specifying certificates, set all values to NULL:
will return an error if attempting to connect and TLS is incorrectly set up.
Even if Connector/C supports TLSv1.3 protocol, it is not possible yet to specify TLSv1.3 cipher suites via cipher parameter.
See Also
mysql_use_result
mysql_use_result 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.
Used to initiate the retrieval of a result set from the last query executed using the mysql_real_query() function on the database connection. Either this or the mysql_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.
Return Value
Returns an unbuffered result set or NULL if an error occurred.
mysql_session_track_get_next retrieves subsequent session state change notifications after mysql_session_track_get_first, called repeatedly until a nonzero value signals end of data.
mysql_session_track_get_first retrieves the first session state change notification from the server, covering schema changes, system variables, and state flags. Added in Connector/C 3.0.
mysql - mysql handle, which was previously allocated by or .
type - type of information. Valid values are
mysql_store_result
mysql_store_result retrieves a complete buffered result set from the last executed MariaDB query, returning NULL on error or for non-SELECT statements.
mysql - a mysql handle, which was previously allocated by or .
Returns a buffered result set from the last executed query.
Returns a buffered result set or NULL in case an error occurred or if the query didn't return data (e.g. when executing an INSERT, UPDATE
The mysql_use_result() function does not transfer the entire result set. Hence, several functions like mysql_num_rows() or mysql_data_seek() cannot be used.
mysql_use_result() will block the current connection until all result sets are retrieved, or result set was released by mysql_free_result().
data - pointer to data, which must be declared as const char *
length - pointer to a size_t variable, which will contain the length of data
mysql_session_track_get_first() retrieves the first session status change information received from the server.
Depending on the specified type the read only data pointer will contain the following information:
SESSION_TRACK_SCHEMA: The name of the default schema (database)
SESSION_TRACK_SYSTEM_VARIABLES: If a session system variable is changed, the first call contains the name of the changed system variable, the second call contains the new value. Both name and value are represented as strings.
SESSION_TRACK_STATE_CHANGE: shows whether the session status has changed. The value is changed as string "1" (changed) or "0" (unchanged).
mysql_set_character_set sets the default character set for a MariaDB Connector/C connection, ensuring mysql_real_escape_string uses the correct encoding.
Syntax
int mysql_set_character_set(MYSQL * mysql,
const char * csname);
2-byte character set for traditional Chinese, Hongkong, Macau and Taiwan
It is strongly recommended to use mysql_set_character_set() instead of SET NAMES ... since mysql_real_escape_string() might fail or deliver unexpected results.
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_option - the option to set. See description below.
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 .
Some of these options can also be set in , 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
MYSQL_INIT_COMMAND: lets you specify a command to execute immediately after connecting (and also after a reconnect if enabled).
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.
Some of these options can also be set as arguments to the function.
MARIADB_OPT_HOST: Hostname or IP address of the server to connect to.
MARIADB_OPT_USER: User to login to the server.
MARIADB_OPT_PASSWORD: Password of the user to login to the server.
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_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_DEFAULT_AUTH: Default authentication client-side plugin to use.
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.
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.
The callback function must match the following signature:
Parameters
Parameter
Type
Description
Variadic Parameters (vary by type)
When type is STATUS_TYPE:
Position
Type
Description
When type is SESSION_TRACK_TYPE:
Position
Type
Description
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.
Added in MariaDB Connector/C 3.3.1 version. See .
MYSQL_READ_DEFAULT_FILE: Read options from an .
MYSQL_READ_DEFAULT_GROUP: Read options from the named from an .
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 are read.
As defined by the , 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
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
MYSQL_OPT_CONNECT_ATTR_DELETE: Deletes a connection attribute for the given key.
MYSQL_OPT_CONNECT_ATTR_ADD: Adds a key/value pair to connection attributes.
MYSQL_OPT_CONNECT_ATTR_RESET: Clears the current list of connection attributes.
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.
unsigned int timeout= 5;
mysql_optionsv(mysql, MYSQL_OPT_CONNECT_TIMEOUT, (void *)&timeout);
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_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_optionsv(mysql, MYSQL_OPT_NONBLOCK, 0);
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_PROTOCOL: Specify the type of client/server protocol. Possible values are:
MYSQL_PROTOCOL_TCP
MYSQL_PROTOCOL_SOCKET
MYSQL_PROTOCOL_PIPE
MYSQL_PROTOCOL_MEMORY.
MARIADB_OPT_FOUND_ROWS: Return the number of matched rows instead of number of changed rows.
mysql_optionsv(mysql, MARIADB_OPT_FOUND_ROWS, 1);
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_optionsv(mysql, MYSQL_OPT_COMPRESS, NULL);
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_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_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 openssl rehash 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_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 openssl rehash 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_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_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.
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.
unsigned int cipher_strength= 128;
mysql_optionsv(mysql, MARIADB_OPT_TLS_CIPHER_STRENGTH, (void*)&cipher_strength);
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.
c mysql_optionsv(mysql, MARIADB_OPT_RESTRICTED_AUTH, (void *)"ed25519,caching_sha2_password");
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_optionsv(mysql, MYSQL_SECURE_AUTH, 1);
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.
If track_type is SESSION_TRACK_SYSTEM_VARIABLES: the variable value.
if MYSQL_READ_DEFAULT_FILE is set to a non-empty string, then it is interpreted as a path to a custom option file, 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.
value for the buffer length.
_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
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.
mysql - a mysql handle, which was previously allocated by mysql_init().
host - can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.
user - the user name.
passwd - If provided or NULL, the server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).
db - if provided will specify the default database to be used when performing queries.
port - specifies the port number to attempt to connect to the server.
unix_socket - specifies the socket or named pipe that should be used.
flags - the flags allows various connection options to be set:
CLIENT_FOUND_ROWS: Return the number of matched rows instead of number of changed rows.
CLIENT_NO_SCHEMA: Forbids the use of database.tablename.column syntax and forces the SQL parser to generate an error.
Establishes a connection to a database server.
Returns a connection handle (same as passed for 1st parameter) or NULL on error. On error, please check and functions for more information.
CLIENT_IGNORE_SPACE: Allows spaces after function names. All function names will become reserved words.
CLIENT_LOCAL_FILES: Allows LOAD DATA LOCAL statements
CLIENT_MULTI_STATEMENTS: Allows the client to send multiple statements in one command. Statements will be divided by a semicolon.
CLIENT_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 CLIENT_MULTI_STATEMENTS is set.