MySQL Connector/Python

raw JSON →
9.6.0 verified Tue May 12 auth: no python install: verified quickstart: verified

MySQL Connector/Python is a self-contained Python driver for communicating with MySQL servers, using an API that is compliant with the Python Database API Specification v2.0 (PEP 249). It also includes an implementation of the X DevAPI for working with the MySQL Document Store. The library is actively maintained, with its latest version (9.6.0) released in January 2026.

pip install mysql-connector-python
error ModuleNotFoundError: No module named 'mysql'
cause The 'mysql-connector-python' package is not installed, the Python environment is incorrect (e.g., virtual environment not activated), or there is a naming conflict with a local file named 'mysql.py'.
fix
Run pip install mysql-connector-python (or pip3 install mysql-connector-python) to install the package. If using a virtual environment, activate it first. Also, ensure no Python script in your project is named mysql.py or mysql.connector.py.
error mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
cause MySQL 8.0 and later versions use 'caching_sha2_password' as the default authentication plugin, which older versions of `mysql-connector-python` or some configurations do not support, leading to a mismatch.
fix
Upgrade mysql-connector-python to a newer version (8.0.11 or higher generally supports it). Alternatively, configure the MySQL user to use the mysql_native_password plugin: ALTER USER 'your_user'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_password'; then FLUSH PRIVILEGES;.
error mysql.connector.errors.OperationalError: 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061)
cause The Python application cannot establish a connection to the MySQL server. This often indicates incorrect connection parameters (host, port, user, password), the MySQL server is not running, or network/firewall issues prevent access.
fix
Verify the host, port, user, and password in your mysql.connector.connect() call. Ensure the MySQL server is running and accessible from where your Python script is executed. Check firewall settings if connecting remotely.
error AttributeError: 'NoneType' object has no attribute 'cursor'
cause This error occurs when the `mysql.connector.connect()` call fails (e.g., due to an `OperationalError` or incorrect credentials) and returns `None`, and subsequent code attempts to call `cursor()` on this `None` object.
fix
Always wrap the mysql.connector.connect() call in a try...except mysql.connector.Error block and ensure the connection object is not None before attempting to create a cursor. Example: try: cnx = mysql.connector.connect(...) except mysql.connector.Error as err: print(f'Connection error: {err}')
gotcha Data Manipulation Language (DML) operations (e.g., INSERT, UPDATE, DELETE) are not automatically committed to the database. You must explicitly call `connection.commit()` after executing DML statements for changes to persist. Data Definition Language (DDL) operations (e.g., CREATE TABLE, ALTER TABLE) are auto-committed.
fix Always call `connection.commit()` after `cursor.execute()` for DML statements within a transaction block, or if `autocommit` is not enabled.
gotcha By default, MySQL Connector/Python attempts to use a C extension for improved performance. If the `libmysqlclient` library is missing or incompatible on your system (e.g., specific Python versions or platforms), this can lead to connection errors or failures. Setting `use_pure=True` in the `connect()` call forces the use of the pure Python implementation.
fix Add `use_pure=True` to your `mysql.connector.connect()` parameters, e.g., `mysql.connector.connect(..., use_pure=True)`.
breaking X DevAPI support, which was previously part of the `mysql-connector-python` package, was separated into its own distinct package (`mysqlx-connector-python`) starting from version 8.3.0.
fix For X DevAPI functionality, install `mysqlx-connector-python` via `pip install mysqlx-connector-python` and import from `mysqlx` instead of `mysql.connector`.
gotcha MySQL Connector/Python does not support old MySQL Server authentication methods. This means it will not work with MySQL server versions prior to 4.1.
fix Ensure your MySQL server version is 4.1 or higher. It is recommended to use MySQL Server version 8.0 or higher with the latest Connector/Python versions.
gotcha Frequent `mysql.connector.errors.OperationalError` often indicates underlying issues such as incorrect database credentials (host, user, password, database), network problems (firewall, unreachable host), or the MySQL server being down or inaccessible.
fix Verify all connection parameters are correct, check network connectivity, ensure the MySQL server is running and accessible from the client, and review MySQL server logs for connection attempts/failures. Implement robust exception handling and connection pooling for production applications.
pip install mysqlx-connector-python
python os / libc variant status wheel install import disk
3.10 alpine (musl) mysql-connector-python - - 0.17s 21.1M
3.10 alpine (musl) telemetry - - 0.43s 33.0M
3.10 alpine (musl) webauthn - - 0.13s 35.6M
3.10 alpine (musl) mysqlx-connector-python - - - -
3.10 slim (glibc) mysql-connector-python - - 0.15s 120M
3.10 slim (glibc) telemetry - - 0.30s 133M
3.10 slim (glibc) webauthn - - 0.09s 135M
3.10 slim (glibc) mysqlx-connector-python - - - -
3.11 alpine (musl) mysql-connector-python - - 0.28s 23.5M
3.11 alpine (musl) telemetry - - 0.60s 36.4M
3.11 alpine (musl) webauthn - - 0.24s 38.7M
3.11 alpine (musl) mysqlx-connector-python - - - -
3.11 slim (glibc) mysql-connector-python - - 0.27s 123M
3.11 slim (glibc) telemetry - - 0.46s 136M
3.11 slim (glibc) webauthn - - 0.18s 138M
3.11 slim (glibc) mysqlx-connector-python - - - -
3.12 alpine (musl) mysql-connector-python - - 0.26s 15.2M
3.12 alpine (musl) telemetry - - 0.76s 28.0M
3.12 alpine (musl) webauthn - - 0.17s 30.3M
3.12 alpine (musl) mysqlx-connector-python - - - -
3.12 slim (glibc) mysql-connector-python - - 0.24s 114M
3.12 slim (glibc) telemetry - - 0.81s 128M
3.12 slim (glibc) webauthn - - 0.18s 129M
3.12 slim (glibc) mysqlx-connector-python - - - -
3.13 alpine (musl) mysql-connector-python - - 0.20s 14.8M
3.13 alpine (musl) telemetry - - 0.75s 27.6M
3.13 alpine (musl) webauthn - - 0.29s 29.9M
3.13 alpine (musl) mysqlx-connector-python - - - -
3.13 slim (glibc) mysql-connector-python - - 0.28s 114M
3.13 slim (glibc) telemetry - - 0.73s 127M
3.13 slim (glibc) webauthn - - 0.19s 129M
3.13 slim (glibc) mysqlx-connector-python - - - -
3.9 alpine (musl) mysql-connector-python - - 0.20s 20.1M
3.9 alpine (musl) telemetry - - 0.40s 31.7M
3.9 alpine (musl) webauthn - - 0.12s 35.4M
3.9 alpine (musl) mysqlx-connector-python - - - -
3.9 slim (glibc) mysql-connector-python - - 0.18s 111M
3.9 slim (glibc) telemetry - - 0.35s 123M
3.9 slim (glibc) webauthn - - 0.10s 126M
3.9 slim (glibc) mysqlx-connector-python - - - -

This quickstart demonstrates how to establish a connection to a MySQL database, create a table (DDL), insert data (DML), and query data using `mysql.connector`. It highlights the importance of `conn.commit()` for data manipulation statements. Database credentials are retrieved from environment variables for security.

import os
import mysql.connector
from mysql.connector import Error

host = os.environ.get('MYSQL_HOST', 'localhost')
user = os.environ.get('MYSQL_USER', 'root')
password = os.environ.get('MYSQL_PASSWORD', 'your_password')
database = os.environ.get('MYSQL_DATABASE', 'test_db')

conn = None
try:
    conn = mysql.connector.connect(
        host=host,
        user=user,
        password=password,
        database=database
    )

    if conn.is_connected():
        print(f"Connected to MySQL database: {database}")
        cursor = conn.cursor()

        # Create a table (DDL - auto-commits)
        cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))")
        print("Table 'users' ensured to exist.")

        # Insert data (DML - requires commit)
        sql_insert = "INSERT INTO users (name, email) VALUES (%s, %s)"
        data_to_insert = ("Alice", "alice@example.com")
        cursor.execute(sql_insert, data_to_insert)
        conn.commit() # Important: Commit changes for DML operations
        print(f"Inserted: {cursor.rowcount} row(s)")

        # Select data
        cursor.execute("SELECT id, name, email FROM users")
        records = cursor.fetchall()
        print("\nData from 'users' table:")
        for row in records:
            print(row)

    else:
        print("Failed to connect to MySQL database.")

except Error as e:
    print(f"Error connecting to MySQL: {e}")
finally:
    if conn and conn.is_connected():
        conn.close()
        print("MySQL connection closed.")