MariaDB Connector/Python

1.1.14 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a MariaDB database, create a table, insert data using parameterized queries, and fetch results. It retrieves connection details from environment variables for secure and flexible deployment. Remember to set `MARIADB_HOST`, `MARIADB_PORT`, `MARIADB_USER`, `MARIADB_PASSWORD`, and `MARIADB_DATABASE`.

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()

view raw JSON →