Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
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.
Quickstart Guide for Connector/C++
MariaDB Connector/C++ allows your C++ applications to connect to MariaDB databases, including support for TLS encryption. It provides an object-oriented design and leverages smart pointers for efficient memory management.
While you can use MariaDB Connector/C for C++ applications, Connector/C++ offers specific advantages for C++ development:
To get started with MariaDB Connector/C++, you'll typically need to:
Download the Connector/C++ library. Look for the appropriate package for your operating system and development environment.
Integrate the library into your C++ project. This usually involves including header files and linking against the library during compilation.
Write C++ code to establish a connection, execute SQL queries, and process results using the object-oriented API.
This page is: Copyright © 2025 MariaDB. All rights reserved.
Feature
Connector/C++
Connector/C
Executes SQL
Yes
Yes
Object-Oriented
Yes
No
Smart Pointers
Yes
No
Implements JDBC API
Yes
No
Quickstart Guide for Connector/C
This guide will help you quickly get started with MariaDB Connector/C, the client library used to connect C/C++ applications to MariaDB and MySQL databases. It's LGPL licensed and is being integrated directly into MariaDB Server distributions.
MariaDB Connector/C is often distributed with MariaDB Server packages, but you can also install it separately.
You can download MariaDB Connector/C packages directly:
From the downloads page: Select your desired version from the main MariaDB Connector/C download page.
By product selection: Choose "C/C++ connector" as the Product on the MariaDB downloads page.
If you're using Linux, the simplest way to install MariaDB Connector/C is via your system's package manager. Your system needs to be configured to install from a MariaDB repository (version 10.2 or later).
You can set up your repository using:
MariaDB Corporation's .
MariaDB Foundation's .
Install with yum/dnf (RHEL, CentOS, Fedora)
For RHEL, CentOS, Fedora, and similar distributions, use yum or dnf:
To install the shared library:
To install the development package (if you're building applications):
Install with apt-get (Debian, Ubuntu)
For Debian, Ubuntu, and similar distributions, use apt-get:
To install the shared library:
To install the development package (if you're building applications):
Install with zypper (SLES, OpenSUSE)
For SLES, OpenSUSE, and similar distributions, use zypper:
To install the shared library:
To install the development package (if you're building applications):
MariaDB Connector/C for Windows is distributed as MSI packages. The installation process is straightforward, with both 32-bit and 64-bit MSI packages available.
If you prefer to build from source, refer to the documentation.
MariaDB Connector/C provides an API that is compatible with MySQL Connector/C for MySQL 5.5.
You can find the function reference at:
An HTML version is also available for download in mariadb-client-doc.zip.
Similar to MariaDB Server, MariaDB Connector/C can read configuration options from client option groups in option files.
For detailed information, see .
Be aware of these potential limitations:
Double-to-string conversion for prepared statements may not work correctly.
Connector versions 3.0.7 and below do not support MySQL 8.0's default authentication protocol, caching_sha2_password. This should be supported in Connector/C 3.0.8 and above.
Report Bugs: If you encounter a bug, please report it via the .
Source Code: The source code is available on GitHub in the .
GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
For licensing questions, see the .
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-develQuickstart Guide for MySQL/OTP (Erlang/OTP Client)
MySQL/OTP is the native Erlang/OTP client for connecting Erlang applications to MariaDB and MySQL databases, offering a direct implementation of the MySQL protocol.
Add MySQL/OTP as a dependency in your rebar.config file (for rebar3 projects):
Erlang
{deps, [
{mysql, ".*", {git, "https://github.com/mysql-otp/mysql-otp.git", {tag, "2.0.0"}}} % Use the latest stable tag
]}.Then, run rebar3 compile.
Here are essential steps for connecting and interacting with your database:
a. Connect:
Erlang
Replace placeholder values with your actual database credentials.
b. Execute Query:
Erlang
c. Close Connection:
Erlang
{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).Quickstart Guide for Connector/J
MariaDB Connector/J is the official Java Database Connectivity (JDBC) driver for connecting Java applications to MariaDB and MySQL databases. It allows Java programs to interact with databases using the standard JDBC API.
See About MariaDB Connector/J for full content.
You can include MariaDB Connector/J in your project using build tools like Maven or Gradle, or by manually adding the JAR file to your project's classpath.
a. Using Maven:
Add the following dependency to your pom.xml file:
b. Using Gradle:
Add the following dependency to your build.gradle file:
c. Manual Installation:
Download the latest stable .jar file from the .
Add the downloaded .jar file to your project's classpath.
Here's a simple Java example demonstrating how to establish a connection and execute a basic query using DriverManager.
Before Running:
Replace your_database_name, your_username, your_password, and your_table_name with your actual database details.
Ensure you have a MariaDB server running and a database/table set up.
MariaDB Connector/J supports various connection string formats, including options for failover and load balancing. The basic format is:
jdbc:mariadb://<hostDescription>[,<hostDescription>...]/[database][?<key1>=<value1>[&<key2>=<value2>]]
For example:
jdbc:mariadb://localhost:3306/mydb
jdbc:mariadb://server1:3306,server2:3306/mydb?failover=true
For production applications, it's highly recommended to use a connection pool to manage database connections efficiently. MariaDB Connector/J can be used with external connection pooling libraries like HikariCP or Apache Commons DBCP, or its own MariaDbPoolDataSource.
MariaDbDataSource: Creates a new connection each time.
MariaDbPoolDataSource: Maintains a pool of connections for reuse.
When using an external pool, configure it to use org.mariadb.jdbc.Driver as the JDBC driver class.
Quickstart guide for MariaDB Connector/ODBC
MariaDB Connector/ODBC is a database driver that allows applications to connect to MariaDB and MySQL databases using the Open Database Connectivity (ODBC) API. It's fully compliant with the ODBC 3.5 standard, open-source (LGPL), and can serve as a drop-in replacement for MySQL Connector/ODBC. It supports both Unicode and ANSI modes and communicates primarily using the MariaDB/MySQL binary protocol.
ODBC (Open Database Connectivity) is a standard API for accessing database management systems (DBMS). It provides a common way for applications to communicate with different databases, abstracting away the specifics of each database's native communication protocol. MariaDB Connector/ODBC acts as the specific bridge for MariaDB.
Installation typically involves downloading the appropriate driver package for your operating system and configuring a Data Source Name (DSN).
a. Windows:
Download: Go to the and download the appropriate .msi installer for your Windows version (32-bit or 64-bit).
Run Installer: Execute the downloaded .msi file and follow the on-screen instructions. This will install the necessary driver files.
Configure DSN:
b. Linux / macOS:
Download: Download the appropriate .deb, .rpm, or .pkg package from the .
Install Package:
Debian/Ubuntu: sudo dpkg -i mariadb-connector-odbc_X.Y.Z.deb
Once the MariaDB ODBC driver is installed and a DSN is configured, applications can connect to your MariaDB database using the standard ODBC API. The exact code will vary depending on the programming language and framework you are using (e.g., C++, Java with JDBC-ODBC Bridge, Python with pyodbc, PHP with odbc extension).
a. Connecting via DSN (Common for many applications):
Many applications and tools (like Microsoft Excel, reporting tools, or C++ applications using ODBC) will allow you to select a configured DSN directly.
b. Connecting via DSN-less Connection String:
You can also provide a full connection string directly in your application without pre-configuring a DSN. This is often used in scripting languages or when you need more dynamic control.
Replace {MariaDB ODBC Driver} with the exact driver name from your odbcinst.ini if different.
Quickstart guide for MysqlConnector for ADO.NET
MariaDB Connector/NET, also known as MySqlConnector, is an ADO.NET data provider that enables .NET applications to connect and interact with MariaDB and MySQL databases. It's written entirely in C# and offers high performance and features specific to MariaDB Server.
Quickstart guide for MariaDB Connector/Node.js
MariaDB Connector/Node.js is a client library that enables Node.js applications to connect and interact with MariaDB and MySQL databases. It's built natively in JavaScript and supports both Promise and Callback APIs, with the Promise API being the default and recommended approach. It is licensed under the LGPL.
Quickstart guide for MariaDB Connector/R2DBC
MariaDB Connector/R2DBC allows Java developers to connect to MariaDB and MySQL databases using the Reactive Relational Database Connectivity (R2DBC) API. This enables non-blocking, asynchronous database operations, which are beneficial for building scalable and responsive applications.
Add the necessary dependency to your project's pom.xml (Maven) or build.gradle (Gradle) file. Choose the dependency based on the R2DBC Specification you are targeting.
a. For R2DBC 1.0.0 Specification (Recommended for new projects):
Quickstart guide for Connector/Ruby
mysql2 gem)While there isn't a separate "MariaDB Connector/Ruby" gem, the widely used mysql2 gem serves as the primary and highly compatible Ruby client for connecting to both MariaDB and MySQL databases. It provides a robust API for database interactions in Ruby applications.
MySqlConnector is licensed under the MIT License. It provides robust connectivity with features like:
Zero-configuration SSL: For MariaDB Server 11.4+.
Server Redirection Logic: Based on the latest MariaDB specification for MariaDB Server 11.3+.
Optimized SET NAMES handling: Avoids unnecessary commands for MariaDB Server 11.5+.
MariaDB GSSAPI Authentication: Support for secure authentication methods.
Asynchronous Operations: Fully supports async/await patterns for non-blocking database interactions.
The recommended way to install MySqlConnector is via NuGet.
a. Using NuGet Package Manager Console (in Visual Studio):
b. Using PackageReference (in your .csproj file):
This section provides C# examples for connecting to MariaDB and performing common database operations.
a. Connection String:
A connection string defines how your application connects to the database. Replace placeholder values with your actual database details.
b. Opening and Closing a Connection:
Always ensure connections are properly opened and closed. The using statement is recommended as it ensures the connection is disposed of correctly, even if errors occur.
c. Executing a SELECT Query:
Use MySqlCommand to define your SQL query and ExecuteReaderAsync to retrieve data.
d. Executing INSERT/UPDATE/DELETE Queries:
Use ExecuteNonQueryAsync for operations that do not return a result set (like INSERT, UPDATE, DELETE). Always use parameterized queries to prevent SQL injection vulnerabilities.
The easiest way to install MariaDB Connector/Node.js is using npm (Node Package Manager):
The Promise API simplifies asynchronous operations with async/await. For optimal performance and resource management, it's recommended to use a connection pool.
a. Create a Connection Pool:
Replace localhost, 3306, your_username, your_password, and your_database_name with your actual database details.
b. Perform Database Operations:
Here's an async function example to get a connection, execute queries, and release the connection back to the pool.
If you need compatibility with older Node.js database drivers (mysql, mysql2), you can use the Callback API.
Error Handling: Always include robust error handling (try...catch for Promises, if (err) for Callbacks) in your database interactions.
Parameterized Queries: Always use parameterized queries (e.g., WHERE status = ?, VALUES (?, ?)) to prevent SQL injection attacks.
Connection Pooling: For production applications, always use a connection pool (mariadb.createPool()) instead of single connections to manage resources efficiently.
conn.release() vs. conn.end(): When using a pool, use conn.release() to return the connection to the pool. Use conn.end() or pool.end() only when gracefully shutting down your application.
Gradle
b. For R2DBC 0.9.1 Specification (for compatibility):
XML
Gradle
This example demonstrates how to establish a connection, execute a query, and process results using the reactive API.
Code snippet
Before Running:
Replace your_username, your_password, your_database_name, and your_table_name with your actual MariaDB server details.
Ensure you have a MariaDB server running and a database/table set up.
Add reactor-core dependency if not already present, as R2DBC heavily relies on Project Reactor.
MariaDB Connector/R2DBC supports a standard R2DBC URL format for connection:
r2dbc:mariadb://[username[:password]@]host[:port][/database][?option=value]
Example:
r2dbc:mariadb://user:pass@localhost:3306/mydb?useBatchMultiSend=true
MariaDB Connector/R2DBC also integrates seamlessly with the Spring Data R2DBC framework, providing a higher-level abstraction for reactive database access, including repositories and entity mapping.
This page is: Copyright © 2025 MariaDB. All rights reserved.
The mysql2 gem provides a Ruby interface to the MariaDB/MySQL C client library (either libmysqlclient or MariaDB Connector/C). It allows Ruby applications to execute SQL queries, fetch results, and manage database connections efficiently. It's available on rubygems.org/gems/mysql2.
Before installing the mysql2 gem, you might need to install development libraries for MariaDB Connector/C or MySQL Client on your system.
a. Install System Dependencies (e.g., on Debian/Ubuntu):
On other systems (Fedora, CentOS, macOS), the package names might differ (e.g., mariadb-devel, mysql-devel).
b. Install the mysql2 gem:
Once the system dependencies are in place, install the gem using Bundler (recommended for Rails/Gemfile projects) or directly via gem install:
Here's how to connect to MariaDB and perform common database operations using the mysql2 gem:
a. Connect to the Database:
Replace localhost, 3306, your_username, your_password, and your_database_name with your actual database details.
b. Execute a SELECT Query:
The results object behaves like an enumerable, allowing you to iterate over rows. Column names are accessible as hash keys.
c. Execute INSERT/UPDATE/DELETE Queries:
For data manipulation, use query. For safety, always use prepared statements or proper escaping for user-provided input.
d. Prepared Statements (Recommended for security and performance):
Prepared statements allow you to separate the SQL query structure from the data, preventing SQL injection and improving performance for repeated queries.
Before Running:
Ensure you have a MariaDB server running and a database/table set up.
Replace placeholder values with your actual database credentials and table/column names.
Error Handling: Always wrap your database operations in begin...rescue...end blocks to catch Mysql2::Error exceptions.
Connection Closing: Ensure your Mysql2::Client connection is closed using client.close in a ensure block to release database resources.
Prepared Statements/Escaping: Never concatenate user-provided strings directly into SQL queries. Use prepared statements with placeholders (?) or client.escape() for string literals.
<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.");
}
}
}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}");
}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.");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).");
}
});
});
});<dependency>
<groupId>org.mariadb</groupId>
<artifactId>r2dbc-mariadb</artifactId>
<version>1.2.x</version> </dependency>// Gradle
implementation 'org.mariadb:r2dbc-mariadb:1.2.x' // Use the latest stable version<dependency>
<groupId>org.mariadb</groupId>
<artifactId>r2dbc-mariadb-0.9.1-spec</artifactId>
<version>1.2.x</version> </dependency>// Gradle
implementation 'org.mariadb:r2dbc-mariadb-0.9.1-spec:1.2.x' // 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.");
}
}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 }Open the ODBC Data Source Administrator:
For 64-bit systems, search for "ODBC Data Sources (64-bit)".
For 32-bit systems, search for "ODBC Data Sources (32-bit)".
Go to the "User DSN" or "System DSN" tab (System DSN is generally preferred for broader application access).
Click "Add...".
Select "MariaDB ODBC Driver" (or "MariaDB ODBC 3.1 Driver" depending on the version) from the list and click "Finish".
A configuration dialog will appear. Fill in the details:
Data Source Name: A descriptive name for your DSN (e.g., MyMariaDBDSN).
TCP/IP Server: localhost or the IP address/hostname of your MariaDB server.
Port: 3306 (default MariaDB port).
User: Your database username.
Password: Your database password.
Database: The specific database you want to connect to.
Click "Test" to verify the connection. Click "OK" to save the DSN.
Red Hat/CentOS: sudo rpm -i mariadb-connector-odbc-X.Y.Z.rpm
macOS: Run the .pkg installer.
Configure odbcinst.ini and odbc.ini:
The installer usually places the driver definition in /etc/odbcinst.ini (or a similar location).
You need to create or modify ~/.odbc.ini (for user DSNs) or /etc/odbc.ini (for system DSNs) to define your data source.
Example odbcinst.ini (Driver Definition - usually installed automatically):
Example odbc.ini (DSN Definition):
Test DSN (Optional): You can use isql (from unixodbc-dev or unixodbc package) to test your DSN:
Quickstart guide for MariaDB Connector/Python
MariaDB Connector/Python is the official Python client library for connecting applications to MariaDB and MySQL databases. It implements the Python DB API 2.0 (PEP-249) standard, ensuring compatibility with common Python database programming patterns. The connector is written in C and Python and relies on the MariaDB Connector/C client library for efficient client-server communication.
isql MyMariaDBDSN your_username your_passwordDriver={MariaDB ODBC Driver};Server=localhost;Port=3306;Database=your_database_name;Uid=your_username;Pwd=your_password;Before installing MariaDB Connector/Python, ensure you have:
Python: Version 3.7 or later.
MariaDB Connector/C: Version 3.1.5 or later (for Connector/Python 1.0) or 3.3.1 or later (for Connector/Python 1.1+). On Windows, this is often handled by the pip installation; on Linux/macOS, you typically need to install libmariadb-dev or equivalent development packages via your system's package manager.
The easiest way to install MariaDB Connector/Python is using pip, Python's package installer:
This command downloads and installs the latest stable version of the connector from PyPI.
Here's a simple Python example demonstrating how to connect to MariaDB, execute queries, and manage transactions.
Before Running:
Replace your_username, your_password, and your_database_name with your actual MariaDB server credentials.
Ensure you have a MariaDB server running and the specified database exists.
The example assumes your_table_name is users with columns id, name, email. Adjust the table/column names as needed.
Parameterized Queries: Always use parameterized queries (e.g., VALUES (?, ?)) to prevent SQL injection vulnerabilities. Parameters are passed as a tuple or list to the execute() method.
Transactions (conn.commit() / conn.rollback()): By default, MariaDB Connector/Python may have autocommit enabled. If you need explicit transaction control, ensure you call conn.commit() to save changes or conn.rollback() to undo them.
Error Handling: Use try...except mariadb.Error blocks to gracefully handle database-related exceptions.
Resource Management: Always close your cursor and connection objects in a finally block to ensure resources are released, even if errors occur.
[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 =pip install mariadb
# Or specifically for Python 3:
# pip3 install mariadbimport mariadb
import sys
# 1. Database Connection Parameters
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()
# --- 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()