mysql-python (Legacy MySQLdb)

1.2.5 · deprecated · verified Thu Apr 16

mysql-python, also widely known as MySQLdb, is a Python 2.x interface to the popular MySQL database server. The last official release, 1.2.5, dates back to 2014 and primarily supports Python versions 2.4 through 2.7. It adheres to the Python Database API Specification v2.0 (PEP 249). For modern Python 3.x development, this library is considered deprecated, with `mysqlclient` (a actively maintained fork providing a compatible API) and `mysql-connector-python` (Oracle's official pure Python driver) being the recommended alternatives.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a MySQL database, create a table, insert data, and fetch results using the `MySQLdb` module. Ensure your MySQL server is running and `MYSQL_HOST`, `MYSQL_USER`, `MYSQL_PASSWORD`, and `MYSQL_DATABASE` environment variables are set with appropriate credentials. Remember to commit changes after DDL and DML operations.

import MySQLdb
import os

try:
    # Establish a connection to the MySQL server
    # Note: mysql-python (MySQLdb) primarily supports Python 2.x. 
    # Use 'passwd' for password and 'db' for database name.
    conn = MySQLdb.connect(
        host=os.environ.get('MYSQL_HOST', 'localhost'),
        user=os.environ.get('MYSQL_USER', 'root'),
        passwd=os.environ.get('MYSQL_PASSWORD', 'password'),
        db=os.environ.get('MYSQL_DATABASE', 'testdb')
    )

    # Create a cursor object to execute queries
    cursor = conn.cursor()

    # 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),
            age INT
        )
    """)
    conn.commit() # Commit changes for DDL operations

    # Insert data
    cursor.execute("INSERT INTO my_table (name, age) VALUES (%s, %s)", ("Alice", 30))
    cursor.execute("INSERT INTO my_table (name, age) VALUES (%s, %s)", ("Bob", 24))
    conn.commit() # Commit changes for DML operations

    print(f"Inserted {cursor.rowcount} records.")

    # Fetch data
    cursor.execute("SELECT id, name, age FROM my_table")
    rows = cursor.fetchall()

    print("\nData in my_table:")
    for row in rows:
        print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")

except MySQLdb.Error as e:
    print(f"Error: {e}")
finally:
    # Close the cursor and connection
    if 'cursor' in locals() and cursor:
        cursor.close()
    if 'conn' in locals() and conn:
        conn.close()
    print("\nConnection closed.")

view raw JSON →