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.
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 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.")