mysqlclient

2.2.8 · active · verified Sun Mar 29

mysqlclient is a Python interface to MySQL that acts as a fork of MySQLdb1, providing Python 3 support and numerous bug fixes. It is a C extension that wraps the official MySQL C API (libmysqlclient), offering superior performance compared to pure-Python drivers. The library currently operates at version 2.2.8 and maintains a healthy release cadence, with at least one new version released in the past three months.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a MySQL database, execute a simple query, create a table, insert data, and retrieve data using `mysqlclient`. Connection parameters are loaded from environment variables for flexibility. Remember to replace placeholder credentials with actual, securely managed values in a production environment.

import MySQLdb
import os

DB_HOST = os.environ.get('MYSQL_HOST', '127.0.0.1')
DB_USER = os.environ.get('MYSQL_USER', 'root')
DB_PASSWORD = os.environ.get('MYSQL_PASSWORD', 'your_password') # Replace with a secure method for production
DB_NAME = os.environ.get('MYSQL_DATABASE', 'testdb')

try:
    # Establish a connection
    conn = MySQLdb.connect(
        host=DB_HOST,
        user=DB_USER,
        password=DB_PASSWORD,
        database=DB_NAME
    )
    cursor = conn.cursor()

    # Execute a query
    cursor.execute("SELECT VERSION();")
    version = cursor.fetchone()
    print(f"Database version: {version[0]}")

    # Example: Create a table (if it doesn't exist)
    cursor.execute("CREATE TABLE IF NOT EXISTS my_table (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))")
    print("Table 'my_table' ensured.")

    # Example: Insert data
    cursor.execute("INSERT INTO my_table (name) VALUES (%s)", ("Test Name",))
    conn.commit()
    print("Data inserted.")

    # Example: Read data
    cursor.execute("SELECT id, name FROM my_table")
    rows = cursor.fetchall()
    for row in rows:
        print(f"ID: {row[0]}, Name: {row[1]}")

finally:
    # Close the cursor and connection
    if 'cursor' in locals() and cursor:
        cursor.close()
    if 'conn' in locals() and conn:
        conn.close()
    print("Database connection closed.")

view raw JSON →