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

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:

  1. Replace your_username, your_password, and your_database_name with your actual MariaDB server credentials.

  2. Ensure you have a MariaDB server running and the specified database exists.

  3. The example assumes your_table_name is users with columns id, 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 the execute() method.

  • Transactions (conn.commit() / conn.rollback()): By default, autocommit is disabled. 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.

  • URI Connections: Version 2.0 supports standard URI connection strings for cleaner configuration.

  • Binary Protocol: Use binary=True for 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?