mysqlclient

raw JSON →
2.2.8 verified Tue May 12 auth: no python install: stale

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.

pip install mysqlclient
error 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`.
fix
Use import MySQLdb in your Python code after installing mysqlclient with pip install mysqlclient.
error 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.
fix
Install 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.
error 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.
fix
1. 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.
error 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.
fix
If 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.
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.
fix Before installing `mysqlclient`, install the necessary system packages. For Debian/Ubuntu: `sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config`. For Red Hat/CentOS: `sudo yum install python3-devel mysql-devel pkgconfig`. For macOS: `brew install mysql pkg-config`. For Windows, ensure 'Build Tools for Visual Studio' and 'MariaDB Connector/C' are installed.
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.
fix Ensure `pkg-config` is installed on your system. For Debian/Ubuntu: `sudo apt-get install pkg-config`. For Red Hat/CentOS: `sudo yum install pkgconfig`.
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.
fix Update your `executemany` calls. For example, change `executemany("INSERT INTO t (data) VALUES (%s)", [1, 2, 3])` to `executemany("INSERT INTO t (data) VALUES (%s)", [(1,), (2,), (3,)])`.
deprecated The `passwd` and `db` keyword arguments in the `MySQLdb.connect()` function are deprecated. They will be removed in future versions.
fix Use `password` and `database` keyword arguments instead.
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.
fix Ensure that each `Connection` object is used by only one thread at a time. If multi-threading is required, establish a separate `Connection` for each thread or use a connection pooling mechanism that manages thread-safe access.
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.
fix Avoid using `Connection.shutdown()` and `Connection.kill()`. If server administration is required, use dedicated MySQL administration tools or SQL commands executed via a standard cursor.
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.
fix If encountering compilation errors on macOS, a common workaround is to modify the `mysql_config` script (usually found in `/usr/local/bin` or a similar path). Specifically, change the `libs` definition from `libs="-L$pkglibdir" libs="$libs -l "` to `libs="-L$pkglibdir" libs="$libs -lmysqlclient -lssl -lcrypto"`.
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
python os / libc status wheel install import disk
3.10 alpine (musl) build_error - - - -
3.10 alpine (musl) - - - -
3.10 slim (glibc) build_error - 2.7s - -
3.10 slim (glibc) - - - -
3.11 alpine (musl) build_error - - - -
3.11 alpine (musl) - - - -
3.11 slim (glibc) build_error - 2.8s - -
3.11 slim (glibc) - - - -
3.12 alpine (musl) build_error - - - -
3.12 alpine (musl) - - - -
3.12 slim (glibc) build_error - 2.7s - -
3.12 slim (glibc) - - - -
3.13 alpine (musl) build_error - - - -
3.13 alpine (musl) - - - -
3.13 slim (glibc) build_error - 2.3s - -
3.13 slim (glibc) - - - -
3.9 alpine (musl) build_error - - - -
3.9 alpine (musl) - - - -
3.9 slim (glibc) build_error - 3.3s - -
3.9 slim (glibc) - - - -

This quickstart demonstrates how to establish a connection to a MySQL database, execute a simple query, create a table, insert data, and retrieve data using `mysqlclient`. Connection parameters are loaded from environment variables for flexibility. Remember to replace placeholder credentials with actual, securely managed values in a production environment.

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