Typing stubs for mysqlclient
types-mysqlclient provides static type annotations (stubs) for the popular `mysqlclient` Python package, which is a MySQL database connector. It enables type checkers like MyPy and Pyright to analyze code using `mysqlclient` for type correctness. This package is part of the typeshed project and is released automatically, typically daily, to PyPI, aiming to provide accurate annotations for `mysqlclient==2.2.*`.
Common errors
-
Failed building wheel for mysqlclient
cause Missing system-level development headers for Python and MySQL, or build tools.fixInstall system dependencies: `sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config` (Ubuntu/Debian) or `sudo yum install python3-devel mysql-devel pkgconfig` (Red Hat/CentOS). -
ImportError: No module named 'mysqlclient'
cause Attempting to import the package name `mysqlclient` directly instead of the `MySQLdb` module it provides.fixChange `import mysqlclient` to `import MySQLdb`. -
pkg-config: not found
cause The `pkg-config` utility, required by `mysqlclient`'s build process to locate libraries, is not installed or not in the system's PATH.fixInstall `pkg-config`: `sudo apt-get install pkg-config` (Ubuntu/Debian) or `sudo yum install pkgconfig` (Red Hat/CentOS). -
(_mysql_exceptions.OperationalError) (1045, "Access denied for user 'youruser'@'localhost' (using password: YES)")
cause Incorrect username, password, or host for the MySQL database connection.fixDouble-check your connection parameters (host, user, password, database) in `MySQLdb.connect()` against your MySQL server configuration. Ensure the user has privileges from the connecting host. -
(_mysql_exceptions.OperationalError) (2006, 'MySQL server has gone away')
cause The connection to the MySQL server was lost, often due to inactivity timeout (`wait_timeout`), a large packet size exceeding `max_allowed_packet`, or the server restarting.fixCheck `wait_timeout` and `max_allowed_packet` server variables. Increase them if necessary. Ensure network stability. Implement connection pooling or re-connection logic in your application.
Warnings
- breaking Stub versions can introduce type-checking breaking changes. While `typeshed` aims for stability, any update to `types-mysqlclient` (even a patch version) might reveal type inconsistencies in your code due to improved or corrected annotations.
- gotcha The `mysqlclient` package (the runtime library) often fails to install with a 'Failed building wheel' error if necessary system-level development headers and libraries are missing. This is not an issue with `types-mysqlclient` itself, but with its runtime dependency.
- gotcha When using `cursor.execute()` with SQL statements that contain literal percent signs (`%`), they must be escaped as `%%` if they are not intended as parameter placeholders. Failure to do so can lead to `TypeError: not all arguments converted during string formatting` or incorrect query execution.
- deprecated The direct use of the low-level `_mysql` module, which is part of the `mysqlclient` package, is discouraged. It is less portable and works at a lower level of abstraction than `MySQLdb`.
Install
-
pip install types-mysqlclient -
pip install mysqlclient -
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config -
sudo yum install python3-devel mysql-devel pkgconfig
Imports
- MySQLdb
import mysqlclient
import MySQLdb
Quickstart
import MySQLdb
import os
host = os.environ.get('MYSQL_HOST', '127.0.0.1')
user = os.environ.get('MYSQL_USER', 'root')
password = os.environ.get('MYSQL_PASSWORD', 'password')
database = os.environ.get('MYSQL_DATABASE', 'testdb')
conn = None
try:
# Establish a connection to the database
conn = MySQLdb.connect(host=host, user=user, password=password, database=database)
print("Successfully connected to MySQL database!")
# Create a cursor object
cursor = conn.cursor()
# Execute a query
cursor.execute("SELECT VERSION();")
# Fetch and print the result
result = cursor.fetchone()
print(f"MySQL Database version: {result[0]}")
# Example: Create a table (if not exists)
cursor.execute("CREATE TABLE IF NOT EXISTS example_table (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255));")
print("Table 'example_table' ensured to exist.")
conn.commit()
# Example: Insert data
cursor.execute("INSERT INTO example_table (name) VALUES (%s);", ("Test Name",))
print("Data inserted.")
conn.commit()
# Example: Select data
cursor.execute("SELECT id, name FROM example_table;")
rows = cursor.fetchall()
print("Data in example_table:")
for row in rows:
print(f" ID: {row[0]}, Name: {row[1]}")
except MySQLdb.Error as e:
print(f"Error connecting to or interacting with MySQL: {e}")
if conn:
conn.rollback()
finally:
if conn:
conn.close()
print("Database connection closed.")