mysql-python (Legacy MySQLdb)
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
-
ImportError: No module named MySQLdb
cause Attempting to import `MySQLdb` on a Python 3.x environment, or `mysql-python` was not successfully installed.fixIf on Python 3.x, switch to `mysqlclient` (`pip install mysqlclient`) or `mysql-connector-python` (`pip install mysql-connector-python`). If on Python 2.x, ensure `mysql-python` installed successfully (check for compilation errors). -
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-xxxx/mysql-python/
cause Missing necessary C development headers for MySQL client libraries (`libmysqlclient-dev`) or Python (`python-dev`), preventing the C extension from compiling.fixInstall system-level development packages. On Debian/Ubuntu: `sudo apt-get install python-dev libmysqlclient-dev`. On RHEL/CentOS: `sudo yum install python-devel mysql-devel` or `sudo dnf install python-devel mysql-devel`. -
AttributeError: 'module' object has no attribute 'connect'
cause This error typically occurs if you've imported `mysql.connector` expecting `MySQLdb` functionality, or if the `MySQLdb` module was only partially loaded.fixEnsure you are using `import MySQLdb` for `mysql-python` and that the installation was successful. If intentionally using `mysql.connector`, install `mysql-connector-python` (`pip install mysql-connector-python`) and use its API.
Warnings
- breaking This library (mysql-python 1.2.5) officially supports Python 2.4-2.7 only. It is not compatible with Python 3.x, and attempts to install or run it on Python 3 will typically fail with `ImportError` or `SyntaxError`.
- gotcha Installation often fails due to missing C development headers for MySQL client libraries or Python itself. This is particularly common on fresh OS installations or minimal Docker images.
- deprecated The `mysql-python` project (MySQLdb) is no longer actively maintained. The last release was in 2014, meaning it receives no new features, performance improvements, or security patches.
Install
-
pip install mysql-python
Imports
- MySQLdb
import mysql.connector
import MySQLdb
Quickstart
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.")