MariaDB Connector/Python
MariaDB Connector/Python is a Python extension that enables Python applications to connect to MariaDB and MySQL databases. It provides a standard DB-API 2.0 interface and offers features like client-side and server-side cursors, prepared statements, and support for various MariaDB-specific features. The current stable version is 1.1.14, with a 2.0.0 release candidate bringing significant new features like async support. Releases occur a few times a year for minor versions, with major versions less frequent.
Warnings
- breaking MariaDB Connector/Python 2.x (currently in release candidate) introduces significant breaking changes from 1.x, particularly concerning asynchronous support, connection string URIs, and potentially API signatures. Code written for 1.x will likely require modifications to work with 2.x.
- gotcha The `mariadb` connector is a native C extension. If pre-compiled wheels are not available for your platform/Python version, or if you're installing from source, you may need to install the MariaDB Connector/C library (e.g., `libmariadb-dev` on Debian/Ubuntu, `mariadb-connector-c-devel` on Fedora/RHEL) on your system before `pip install mariadb`.
- gotcha Always use parameterized queries (e.g., `cursor.execute("INSERT INTO table VALUES (?) ", (value,))`) instead of string formatting or f-strings for passing user-supplied data into SQL queries. Failing to do so makes your application vulnerable to SQL injection attacks.
- gotcha Connections and cursors should always be properly closed to release database resources. Failing to do so can lead to resource exhaustion and performance issues, especially in high-traffic applications.
Install
-
pip install mariadb -
pip install --pre mariadb
Imports
- mariadb
import mariadb
- Error
import mariadb.Error
Quickstart
import mariadb
import os
host = os.environ.get('MARIADB_HOST', '127.0.0.1')
port = int(os.environ.get('MARIADB_PORT', 3306))
user = os.environ.get('MARIADB_USER', 'root')
password = os.environ.get('MARIADB_PASSWORD', '')
database = os.environ.get('MARIADB_DATABASE', 'test_db')
conn = None
cursor = None
try:
# Connect to MariaDB Platform
conn = mariadb.connect(
user=user,
password=password,
host=host,
port=port,
database=database
)
# Get a cursor
cursor = conn.cursor()
# Create a table
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))")
conn.commit()
# Insert data
cursor.execute("INSERT INTO users (name) VALUES (?) ", ("Alice",))
cursor.execute("INSERT INTO users (name) VALUES (?) ", ("Bob",))
conn.commit()
# Query data
cursor.execute("SELECT id, name FROM users")
for (id_val, name) in cursor:
print(f"ID: {id_val}, Name: {name}")
except mariadb.Error as e:
print(f"Error connecting to or interacting with MariaDB Platform: {e}")
finally:
if cursor:
cursor.close()
if conn:
conn.close()