mysqlclient
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.
Common errors
-
ModuleNotFoundError: No module named 'MySQLdb'
cause The `mysqlclient` library, despite its package name, provides the `_mysql` C extension and is typically imported in Python code using `import MySQLdb`.fixUse `import MySQLdb` in your Python code after installing `mysqlclient` with `pip install mysqlclient`. -
EnvironmentError: mysql_config not found
cause Building `mysqlclient` from source requires the MySQL client development headers and libraries (which include `mysql_config`) to be installed on your system. This error typically occurs on Linux/macOS when these system-level dependencies are missing.fixInstall the necessary MySQL development packages for your operating system. For Debian/Ubuntu, use `sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config`. For Red Hat/CentOS, use `sudo yum install python3-devel mysql-devel pkgconfig`. On macOS with Homebrew, you may need `brew install mysql-connector-c` or ensure MySQL is linked correctly. -
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
cause This error indicates that the Python application could not establish a TCP/IP connection to the MySQL server. Common reasons include the MySQL server not running, an incorrect host or port, a firewall blocking the connection, or the MySQL server not being configured to accept network connections.fix1. Ensure the MySQL server is running. 2. Verify the host and port are correct in your connection string (e.g., `host='127.0.0.1'`, `port=3306`). 3. Check your system's firewall rules to ensure port 3306 is open. 4. In `my.cnf` (MySQL configuration), ensure `bind-address` is correctly set (e.g., `0.0.0.0` or the specific IP) and `skip-networking` is commented out. -
AttributeError: module 'mysql.connector' has no attribute 'connect'
cause This error often occurs when `mysqlclient` is installed, but the Python code is attempting to use the connection syntax specific to `mysql-connector-python` (e.g., `mysql.connector.connect()`). `mysqlclient` does not expose a `connector` module in this way.fixIf `mysqlclient` is installed, the correct way to establish a connection is `import MySQLdb; conn = MySQLdb.connect(host='...', user='...', password='...', database='...')`. If you intend to use `mysql.connector`, you must install it (`pip install mysql-connector-python`) and import it as `import mysql.connector`.
Warnings
- breaking Installation via `pip install mysqlclient` often fails without pre-installed system-level MySQL client development headers, a C/C++ compiler, and `pkg-config` (on POSIX systems). This is because `mysqlclient` is a C extension that needs to compile against native libraries.
- breaking In version 2.2.0, `mysqlclient` switched from using `mysql_config` to `pkg-config` for discovering compiler and linker flags during installation. If `pkg-config` is not installed or configured correctly, compilation will fail.
- breaking The `Cursor.executemany()` method's argument format changed in version 2.2.0. It now expects a sequence of tuples, even for single-value inserts, instead of a sequence of scalar values.
- deprecated The `passwd` and `db` keyword arguments in the `MySQLdb.connect()` function are deprecated. They will be removed in future versions.
- gotcha As of v2.2.8, `mysqlclient` offers experimental support for free-threaded Python (importing `MySQLdb` doesn't enable the GIL). However, the library explicitly states that it *does not* support simultaneous operations on a single `Connection` object from multiple threads concurrently. Doing so will result in undefined behavior.
- deprecated The `Connection.shutdown()` and `Connection.kill()` methods are deprecated, as the underlying MySQL C API functions (`mysql_shutdown()` and `mysql_kill()`) were removed in MySQL 8.3. These methods will emit a `DeprecationWarning` in future versions.
- gotcha On macOS, certain versions of `mysql-connector-c` installed via Homebrew or official packages may have incorrect default configuration options, causing `mysqlclient` compilation errors. This often manifests as linker errors related to `ssl` or `crypto` libraries.
Install
-
pip install mysqlclient -
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config pip install mysqlclient -
sudo yum install python3-devel mysql-devel pkgconfig pip install mysqlclient -
brew install mysql pkg-config pip install mysqlclient
Imports
- MySQLdb
import _mysql
import MySQLdb
- connect
from MySQLdb import connect
Quickstart
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.")