Database/MySQL: ImportError: No module named MySQLdb in Python 3
This error occurs when Python tries to import the legacy Python 2 MySQLdb driver in Python 3. Install mysqlclient (pip install mysqlclient) or use pure-Python PyMySQL with pymysql.install_as_MySQLdb().
Root Cause Analysis
This error occurs when Python database scripts, Django projects, or SQLAlchemy database URIs attempt to connect to a MySQL or MariaDB database using the default mysql:// driver, triggering an import of the legacy MySQLdb C-extension.
Root Cause 1: Legacy MySQLdb Lack of Python 3 Compatibility
The original MySQLdb package (MySQL-python) was built for Python 2.x and has been unmaintained for over a decade. It does not support Python 3. When Python 3 frameworks (such as Django's default django.db.backends.mysql engine or SQLAlchemy's mysql:// dialect) attempt import MySQLdb, Python fails with ImportError: No module named 'MySQLdb' or ModuleNotFoundError: No module named 'MySQLdb'.
Root Cause 2: Missing mysqlclient Binary Driver
The modern, official Python 3 fork of MySQLdb is published on PyPI under the name mysqlclient. However, mysqlclient compiles C-extensions during installation, requiring system C development headers (default-libmysqlclient-dev on Debian/Ubuntu, mysql-connector-c on macOS, or Visual C++ Build Tools on Windows). When installation fails or is skipped, the driver remains absent.
Root Cause 3: Default Django MySQL Backend Configuration
Django's built-in MySQL backend django.db.backends.mysql hardcodes an import of MySQLdb upon database initialization. If neither mysqlclient nor a PyMySQL monkey-patch is present in __init__.py, Django fails during ./manage.py runserver or ./manage.py migrate.
Root Cause 4: SQLAlchemy Connection URI Dialect Specification
Using the generic URI mysql://user:pass@localhost/dbname causes SQLAlchemy to search for MySQLdb. Specifying the explicit driver dialect (e.g. mysql+pymysql://) is required when using pure-Python drivers.
Reproduction Code (MCVE)
# Simulating import failure of legacy MySQLdb in Python 3 environment
class MockPython3Environment:
def import_driver(self, driver_name: str):
if driver_name == "MySQLdb":
raise ImportError(
"ImportError: No module named 'MySQLdb'. "
"The legacy MySQL-python driver does not support Python 3. "
"Install 'mysqlclient' or use 'pymysql.install_as_MySQLdb()'."
)
env = MockPython3Environment()
env.import_driver("MySQLdb")
Solution 1: Install mysqlclient or Use Pure-Python PyMySQL
Install the modern C-based mysqlclient package via pip, or install pymysql and patch the MySQLdb namespace.
import sys
# Solution 1: Use PyMySQL as a drop-in replacement for MySQLdb
# In production:
# pip install pymysql
# In your project __init__.py:
# import pymysql
# pymysql.install_as_MySQLdb()
# Standalone demonstration of the PyMySQL compatibility layer pattern
class MockPyMySQL:
@staticmethod
def install_as_MySQLdb():
# Maps pymysql into sys.modules as MySQLdb
print("PyMySQL registered as drop-in replacement for MySQLdb.")
return True
pymysql_driver = MockPyMySQL()
success = pymysql_driver.install_as_MySQLdb()
assert success is True
Solution 2: Configure SQLAlchemy with Explicit PyMySQL Dialect
Specify mysql+pymysql:// in your database connection URL to instruct SQLAlchemy to use the PyMySQL driver directly.
# Solution 2: SQLAlchemy Connection URI configuration
database_uri = "mysql+pymysql://db_user:secure_pass@localhost:3306/production_db"
print("Configured SQLAlchemy Connection String:")
print(database_uri)
assert "mysql+pymysql://" in database_uri
When installing mysqlclient on Linux Docker containers (like python:3.11-slim), always install the prerequisite build tools first: apt-get update && apt-get install -y default-libmysqlclient-dev build-essential pkg-config. If you want to avoid native C compiler dependencies in Docker containers entirely, pymysql (pip install pymysql cryptography) is a 100% pure-Python solution.
Note de reproductibilité : Cette erreur dépend du système d'exploitation hôte, de la disponibilité des compilateurs C (Visual Studio C++ / gcc) et des bibliothèques clientes MySQL/MariaDB installées.
Contrast mysqlclient with mysql-connector-python: mysqlclient is the high-performance C-wrapper fork of MySQLdb (recommended by Django); mysql-connector-python is Oracle's official pure-Python driver (mysql+mysqlconnector:// in SQLAlchemy).