MySQL Connector/Python
MySQL Connector/Python is a self-contained Python driver for connecting to MySQL servers. It implements the Python Database API Specification v2.0 (PEP 249) and also includes an X DevAPI implementation for working with the MySQL Document Store. The library receives regular updates, with version 9.6.0 released in January 2026, and typically sees new major versions every few months.
Warnings
- gotcha Always call `connection.commit()` after Data Manipulation Language (DML) operations (INSERT, UPDATE, DELETE) to persist changes to the database. DDL operations (CREATE TABLE) may auto-commit, but explicit commit is safer for DML. Failure to commit will result in data not being saved.
- breaking Older Python versions (e.g., Python 3.8, 3.9) are no longer supported in recent releases of mysql-connector-python. For example, Python 3.8 was removed in 9.1.0, and 3.9 was removed in 9.3.0. Python 3.13+ has stricter SSL validation (ssl.VERIFY_X509_STRICT) requiring RFC-5280 compliant certificates.
- gotcha Always use parameterized queries (e.g., `INSERT INTO mytable (name) VALUES (%s)`, passing `("value",)` as the second argument to `cursor.execute()`) to prevent SQL injection vulnerabilities. Do not format SQL strings directly with f-strings or `.format()` when incorporating user-provided values.
- gotcha It is crucial to explicitly close both the `cursor` and `connection` objects to release database resources, especially in long-running applications. Failing to do so can lead to resource exhaustion or unexpected behavior.
- gotcha MySQL Connector/Python uses a C extension by default if available (since 8.0.0+). Mixing cursor types from different implementations (C extension vs. pure Python) with connection objects can lead to `ProgrammingError` if they are not compatible.
- gotcha The X DevAPI functionality requires the `protobuf` package. If you intend to use X DevAPI features and encounter import errors or unexpected behavior, `protobuf` might be missing or an incompatible version.
Install
-
pip install mysql-connector-python -
pip install mysql-connector-python[telemetry] -
pip install mysql-connector-python[webauthn]
Imports
- mysql.connector
import mysql.connector
- mysql.connector.connect
import mysql.connector cnx = mysql.connector.connect(...)
Quickstart
import mysql.connector
import os
try:
# Establish the connection
cnx = mysql.connector.connect(
host=os.environ.get('MYSQL_HOST', 'localhost'),
user=os.environ.get('MYSQL_USER', 'root'),
password=os.environ.get('MYSQL_PASSWORD', 'your_password'), # Use a strong password in production
database=os.environ.get('MYSQL_DATABASE', 'testdb')
)
if cnx.is_connected():
print(f"Connected to MySQL database: {cnx.database}")
# Create a cursor object
cursor = cnx.cursor()
# Execute a query (DDL - auto-commits in many cases, but explicit commit is good practice)
cursor.execute("CREATE TABLE IF NOT EXISTS mytable (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))")
cnx.commit() # Commit DDL changes if not auto-committed
print("Table 'mytable' ensured to exist.")
# Insert data (DML - requires explicit commit)
insert_query = "INSERT INTO mytable (name) VALUES (%s)"
data = ("Test Name",)
cursor.execute(insert_query, data)
cnx.commit() # IMPORTANT: Commit DML changes
print(f"Inserted 1 row. Last ID: {cursor.lastrowid}")
# Query data
cursor.execute("SELECT id, name FROM mytable")
records = cursor.fetchall()
for row in records:
print(f"ID: {row[0]}, Name: {row[1]}")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
# Close cursor and connection
if 'cursor' in locals() and cursor is not None:
cursor.close()
if 'cnx' in locals() and cnx.is_connected():
cnx.close()
print("MySQL connection closed.")