asyncmy - A fast asyncio MySQL Driver

0.2.11 · active · verified Mon Apr 13

asyncmy is a high-performance asynchronous MySQL/MariaDB driver for Python, leveraging `asyncio`. It reuses much of the `PyMySQL` and `aiomysql` codebase but significantly boosts performance by rewriting its core protocol in Cython. The library offers an API compatible with `aiomysql` and supports advanced features like the MySQL replication protocol. It is actively maintained, with releases typically occurring as new features or performance improvements are integrated.

Warnings

Install

Imports

Quickstart

This example demonstrates connecting to a MySQL database, executing DDL and DML operations, and fetching results using a DictCursor. It uses environment variables for connection parameters and ensures proper resource cleanup using `async with` and a `finally` block.

import asyncio
import os
from asyncmy import connect
from asyncmy.cursors import DictCursor

async def main():
    conn = await connect(
        host=os.environ.get('MYSQL_HOST', '127.0.0.1'),
        user=os.environ.get('MYSQL_USER', 'root'),
        password=os.environ.get('MYSQL_PASSWORD', ''),
        db=os.environ.get('MYSQL_DB', 'test_db'),
        port=int(os.environ.get('MYSQL_PORT', 3306))
    )
    try:
        async with conn.cursor(cursor=DictCursor) as cursor:
            await cursor.execute("CREATE DATABASE IF NOT EXISTS test_db")
            await cursor.execute("USE test_db")
            await cursor.execute(
                """
                CREATE TABLE IF NOT EXISTS users (
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    name VARCHAR(255),
                    email VARCHAR(255)
                )
                """
            )
            await cursor.execute(
                "INSERT INTO users (name, email) VALUES (%s, %s)",
                ("Alice", "alice@example.com")
            )
            await cursor.execute("SELECT id, name, email FROM users WHERE name = %s", ("Alice",))
            result = await cursor.fetchone()
            print(f"Fetched user: {result}")
    finally:
        await conn.close()

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →