MySQL Connector/Python (RF variant)

2.2.2 · abandoned · verified Thu Apr 16

An old, unmaintained variant of the pure Python MySQL driver for Python, implementing the DB API v2.0 specification (PEP-249). This package was released to PyPI to address distribution issues with the official 'mysql-connector-python' around 2015-2017. It is currently at version 2.2.2 and has not been updated since February 2017.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a MySQL database, create a table, insert data, and query data using the `mysql.connector` module. It follows the standard Python DB-API 2.0 pattern and includes basic error handling and proper resource cleanup.

import mysql.connector
import os

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

try:
    # Establish a connection
    cnx = mysql.connector.connect(
        host=host,
        user=user,
        password=password,
        database=database
    )

    if cnx.is_connected():
        print("Successfully connected to MySQL database.")

        cursor = cnx.cursor()
        # Create a table (if it doesn't exist)
        cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))")
        cnx.commit()
        print("Table 'users' ensured to exist.")

        # Insert data
        add_user = ("INSERT INTO users (name, email) VALUES (%s, %s)")
        data_user = ("John Doe", "john.doe@example.com")
        cursor.execute(add_user, data_user)
        cnx.commit()
        print("Data inserted.")

        # Query data
        cursor.execute("SELECT id, name, email FROM users")
        for (id, name, email) in cursor:
            print(f"ID: {id}, Name: {name}, Email: {email}")

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

except mysql.connector.Error as err:
    print(f"Error: {err}")

finally:
    if 'cnx' in locals() and cnx.is_connected():
        cursor.close()
        cnx.close()
        print("MySQL connection closed.")

view raw JSON →