asyncmy - A fast asyncio MySQL Driver
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
- gotcha On Windows, `asyncmy` uses Cython extensions which require Microsoft C++ Build Tools to be installed for successful installation via pip. Without these tools, installation may fail or result in a non-optimized pure-Python fallback.
- gotcha Always ensure connections and cursors are properly closed to prevent resource leaks. While `async with` statements handle this for contexts, direct `connect()` calls require an explicit `await conn.close()`.
- gotcha Common `asyncio` pitfalls like 'fire and forget' tasks (not awaiting coroutines) or blocking the event loop with synchronous operations can lead to unexpected behavior, lost exceptions, or reduced performance. `asyncmy` operations are all awaitable and should be used within an `asyncio` event loop.
- breaking The `loop` argument for `asyncmy.connect()` and `asyncmy.create_pool()` was removed in version 0.2.1, as passing an explicit event loop is generally no longer necessary or recommended in modern `asyncio`.
Install
-
pip install asyncmy -
pip install asyncmy # On Windows, requires Microsoft C++ Build Tools
Imports
- connect
from asyncmy import connect
- create_pool
from asyncmy import create_pool
- DictCursor
from asyncmy.cursors import DictCursor
- BinLogStream
from asyncmy.replication import BinLogStream
Quickstart
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())