MySQL Connector/Python

9.6.0 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a MySQL database, create a table, insert data using parameterized queries, retrieve data, and properly close resources. It uses environment variables for credentials, a best practice for security.

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

view raw JSON →