Connector/Python Guide
Quickstart guide for MariaDB Connector/Python
Quickstart Guide: MariaDB Connector/Python
MariaDB Connector/Python is the official Python client library for connecting applications to MariaDB and MySQL databases. It implements the Python DB API 2.0 (PEP-249) standard, ensuring compatibility with common Python database programming patterns.
Version 2.0 offers flexible distribution options:
Pure Python - Works everywhere, no compiler or dependencies required
C extension - Maximum performance (2-12× faster on data-heavy workloads)
Pre-compiled wheels - No MariaDB Connector/C installation needed
Async/await support - Native asynchronous operations for modern Python applications
API Reference
Connection API - Connection parameters, methods, and attributes
Cursor API - Cursor parameters, methods, and attributes
Connection Pooling API - Pool configuration and usage
1. Prerequisites
Before installing MariaDB Connector/Python, ensure you have:
Python: Version 3.9 or later
MariaDB Connector/C: Version 3.3.1 or later (optional - only required for C extension from source)
2. Installation
Choose the installation option that best fits your needs:
Pure Python (recommended for most users):
Pre-compiled binary wheels (best for production):
C extension from source (maximum performance):
3. Basic Usage
Here's a simple Python example demonstrating how to connect to MariaDB, execute queries, and manage transactions.
Using Dictionary Configuration (All Versions):
Using URI Connection String (Since Version 2.0):
Before Running:
Replace
your_username,your_password, andyour_database_namewith your actual MariaDB server credentials.Ensure you have a MariaDB server running and the specified database exists.
The example assumes
your_table_nameisuserswith columnsid,name,email. Adjust the table/column names as needed.
Important Notes:
Parameterized Queries: Always use parameterized queries (e.g.,
VALUES (?, ?)) to prevent SQL injection vulnerabilities. Parameters are passed as a tuple or list to theexecute()method.Transactions (
conn.commit()/conn.rollback()): By default, autocommit is disabled. Callconn.commit()to save changes orconn.rollback()to undo them.Error Handling: Use
try...except mariadb.Errorblocks to gracefully handle database-related exceptions.Resource Management: Always close your
cursorandconnectionobjects in afinallyblock to ensure resources are released, even if errors occur.URI Connections: Version 2.0 supports standard URI connection strings for cleaner configuration.
Binary Protocol: Use
binary=Truefor prepared statements and better performance with repeated queries.
4. Async/Await Support (New in 2.0)
For modern async applications (FastAPI, Starlette, etc.):
Async Connection Pool:
Further Resources:
Last updated
Was this helpful?

