PyMySQL

1.1.2 · active · verified Sat Mar 28

PyMySQL is a pure-Python MySQL client library, fully compliant with PEP 249 (Python Database API Specification v2.0). It enables Python applications to connect to MySQL and MariaDB databases without requiring binary extensions. The library is actively maintained, with version 1.1.2 released on August 24, 2025, and supports standard DB-API 2.0 features like cursors, transactions, and parameterized queries.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a MySQL database, insert a record, commit the transaction, and fetch data using `pymysql`. It uses `DictCursor` for results as dictionaries and includes error handling and proper connection closing. Remember that `PyMySQL` does not autocommit by default, so explicit `connection.commit()` is necessary.

import pymysql.cursors
import os

# Configure connection details (replace with your actual database info or environment variables)
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', 'testdb')

try:
    # Connect to the database
    connection = pymysql.connect(host=host,
                                 user=user,
                                 password=password,
                                 database=database,
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    print(f"Successfully connected to MySQL database: {database}")

    with connection.cursor() as cursor:
        # Example: Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@example.com', 'super_secret'))

        # connection is not autocommit by default. So you must commit to save your changes.
        connection.commit()
        print(f"Inserted {cursor.rowcount} row(s).")

        # Example: Read a single record
        sql = "SELECT `id`, `email`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@example.com',))
        result = cursor.fetchone()
        print(f"Fetched record: {result}")

except pymysql.Error as e:
    print(f"Error connecting or querying MySQL: {e}")
finally:
    if 'connection' in locals() and connection.open:
        connection.close()
        print("Database connection closed.")

view raw JSON →