Typing stubs for mysqlclient

2.2.0.20260408 · active · verified Thu Apr 16

types-mysqlclient provides static type annotations (stubs) for the popular `mysqlclient` Python package, which is a MySQL database connector. It enables type checkers like MyPy and Pyright to analyze code using `mysqlclient` for type correctness. This package is part of the typeshed project and is released automatically, typically daily, to PyPI, aiming to provide accurate annotations for `mysqlclient==2.2.*`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a MySQL database using the `MySQLdb` module (provided by `mysqlclient`), execute a simple query, create a table, insert data, and fetch results. It includes basic error handling and uses environment variables for sensitive connection details, which is a common practice in production environments. Ensure `mysqlclient` and its system dependencies are installed before running.

import MySQLdb
import os

host = os.environ.get('MYSQL_HOST', '127.0.0.1')
user = os.environ.get('MYSQL_USER', 'root')
password = os.environ.get('MYSQL_PASSWORD', 'password')
database = os.environ.get('MYSQL_DATABASE', 'testdb')

conn = None
try:
    # Establish a connection to the database
    conn = MySQLdb.connect(host=host, user=user, password=password, database=database)
    print("Successfully connected to MySQL database!")

    # Create a cursor object
    cursor = conn.cursor()

    # Execute a query
    cursor.execute("SELECT VERSION();")

    # Fetch and print the result
    result = cursor.fetchone()
    print(f"MySQL Database version: {result[0]}")

    # Example: Create a table (if not exists)
    cursor.execute("CREATE TABLE IF NOT EXISTS example_table (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255));")
    print("Table 'example_table' ensured to exist.")
    conn.commit()

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

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

except MySQLdb.Error as e:
    print(f"Error connecting to or interacting with MySQL: {e}")
    if conn:
        conn.rollback()
finally:
    if conn:
        conn.close()
        print("Database connection closed.")

view raw JSON →