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...
Complete MariaDB Connectors guide. Complete reference for client libraries in Python, Java, Node.js, C, C++, ODBC, and R languages for production use.
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.
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.
#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;
}
Build MariaDB Connector/C from source. Download the package from MariaDB downloads or get the latest development version from the Connector/C GitHub repository.
#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)#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)Quickstart Guide for MySQL/OTP (Erlang/OTP Client)
{deps, [
{mysql, ".*", {git, "https://github.com/mysql-otp/mysql-otp.git", {tag, "2.0.0"}}} % Use the latest stable tag
]}.{ok, Pid} = mysql:start_link([{host, "localhost"}, {user, "myuser"}, {password, "mypass"}, {database, "mydb"}]).% 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]).mysql:stop(Pid).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 supports loadable and built-in plugins across four categories: connection, pvio, I/O, and authentication, including remote_io and multiple auth methods.
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.
mysql_change_user changes the authenticated user and default database on an existing connection, resetting session state including transactions, temporary tables, and locks.
#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;
}#include <mariadb_rpl.h>
int mariadb_rpl_optionsv(MARIADB_RPL *rpl,
enum mariadb_rpl_option option,
...);# 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;
}Quickstart guide for MariaDB Connector/Node.js
npm install mariadbconst 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.");Quickstart guide for MariaDB Connector/R2DBC
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.
Quickstart Guide for Connector/J
MARIADB_CLIENT_VERSION: The client version in literal representation.Parameter type: const char *.MARIADB_CONNECTION_MARIADB_CHARSET_INFO: Retrieves character set information for given connection. Parameter type: const MY_CHARSET_INFO *.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 versionstring 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 mysql2require '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 versionimport 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.");
}
}
}sudo dpkg -i mariadb-connector-odbc_X.Y.Z.debisql MyMariaDBDSN your_username your_passwordDriver={MariaDB ODBC Driver};Server=localhost;Port=3306;Database=your_database_name;Uid=your_username;Pwd=your_password;field_1:field_2:field_nflag[,modifier,modifier,...,modifier]CMakeFilescmake ../connector_c -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/localcmake .. -D{PLUGIN_NAME}_PLUGIN_TYPE=[STATIC|DYNAMIC|OFF]cmake .. -DCLIENT_PLUGIN_{PLUGIN_NAME}=[STATIC|DYNAMIC|OFF]sudo yum install MariaDB-sharedsudo yum install MariaDB-develsudo apt-get install libmariadb3sudo apt-get install libmariadb-devsudo zypper install MariaDB-sharedsudo zypper install MariaDB-develAll enumerations and preprocessor definitions for the Binglog/Replication API are defined in include/mariadb_rpl.h.
Complete MariaDB installation guide. Complete setup instructions for Linux, Windows, and macOS with configuration and verification for production use.
[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 =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)sudo apt install curlsudo yum install curlsudo zypper install curl$ 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$ sudo apt install curl$ sudo yum install curl$ sudo zypper install curlcurl -LsSO https://r.mariadb.com/downloads/mariadb_repo_setupecho "${checksum} mariadb_repo_setup" \
| sha256sum -c -chmod +x mariadb_repo_setupsudo yum install MariaDB-shared MariaDB-develsudo apt install libmariadb3 libmariadb-devsudo zypper install MariaDB-shared MariaDB-develsudo ./mariadb_es_repo_setup --token="CUSTOMER_DOWNLOAD_TOKEN" --apply \
--mariadb-server-version="10.6"sudo ./mariadb_repo_setup \
--mariadb-server-version="mariadb-10.6"mariadb_config --cc_version3.4.10sudo yum install MariaDB-sharedsudo yum install MariaDB-develsudo apt-get install libmariadb3sudo apt-get install libmariadb-devsudo zypper install MariaDB-sharedsudo zypper install MariaDB-develReference 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.
usersidnameemailconn.rollback()pip install mariadbpip 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())All structures and type definitions for the Binglog/Replication API are defined in include/mariadb_rpl.h.
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.
DELETE_ROWS_EVENT_V125 (0x19)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;
};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_optionsv(mysql, MYSQL_INIT_COMMAND, (void *)"CREATE TABLE test.t1(a int)");
mysql_optionsv(mysql, MYSQL_INIT_COMMAND, (void *)"SET @value := 1");mysql_optionsv(mysql, MARIADB_OPT_HOST, (void *)"dbserver.example.com");mysql_optionsv(mysql, MARIADB_OPT_USER, (void *)"myuser");mysql_optionsv(mysql, MARIADB_OPT_PASSWORD, (void *)"horsebattery");mysql_optionsv(mysql, MYSQL_OPT_SSL_KEY, (void *)"certs/client-key.pem");mysql_optionsv(mysql, MYSQL_OPT_SSL_CERT, (void *)"certs/client-cert.pem");mysql_optionsv(mysql, MYSQL_DEFAULT_AUTH, (void *)"ed25519");mysql_optionsv(mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, 1);mysql_optionsv(mysql, MARIADB_OPT_STATUS_CALLBACK, (void *)my_status_callback, (void *)user_data);void status_callback(void *data, enum enum_mariadb_status_info type, ..)mysql_optionsv(mysql, MARIADB_OPT_RPL_REGISTER_REPLICA, (void *)"replica-host.example.com", (unsigned int)3306);mysql_optionsv(mysql, MYSQL_OPT_CONNECT_ATTR_DELETE, (void *)"app_version");mysql_optionsv(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, (void *)"app_version", (void *)"2.0.1");mysql_optionsv(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);int mysql_optionsv(MYSQL * mysql,
enum mysql_option,
const void * arg,
...);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));enum mysql_protocol_type prot_type= MYSQL_PROTOCOL_SOCKET;
mysql_optionsv(mysql, MYSQL_OPT_PROTOCOL, (void *)&prot_type);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);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.
echo %WINDIR%mysql_optionsv(mysql, MYSQL_READ_DEFAULT_FILE, (void *)"./my_conf.cnf");mysql_optionsv(mysql, MYSQL_READ_DEFAULT_GROUP, NULL);mysql_optionsv(mysql, MYSQL_READ_DEFAULT_GROUP, (void *)"my_section");[client-mariadb]
...
!include /etc/mysql/dbserver1.cnf[client-mariadb]
...
!includedir /etc/my.cnf.d/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=1GBmy_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=1073741824my_bool (*set_option)(MYSQL *mysql, const char *config_option, const char *config_value);