{"id":1312,"library":"aiomysql","title":"aiomysql","description":"aiomysql is a MySQL driver for asyncio, enabling asynchronous interaction with MySQL databases using Python's `async`/`await` syntax. It provides a familiar DB-API 2.0-like interface adapted for asyncio. The current version is 0.3.2. Releases are infrequent, typically driven by critical bug fixes, `PyMySQL` updates, or community contributions.","status":"active","version":"0.3.2","language":"en","source_language":"en","source_url":"https://github.com/aio-libs/aiomysql","tags":["database","mysql","async","asyncio","db-api"],"install":[{"cmd":"pip install aiomysql","lang":"bash","label":"Install aiomysql"}],"dependencies":[],"imports":[{"symbol":"connect","correct":"import aiomysql\n\nconn = await aiomysql.connect(...)"},{"note":"While `from aiomysql import DictCursor` often works due to convenience imports, `from aiomysql.cursors import DictCursor` is the explicit and recommended path for cursor types.","wrong":"from aiomysql import DictCursor","symbol":"DictCursor","correct":"from aiomysql.cursors import DictCursor"},{"symbol":"create_pool","correct":"import aiomysql\n\npool = await aiomysql.create_pool(...)"}],"quickstart":{"code":"import asyncio\nimport os\nimport aiomysql\n\nasync def main():\n    # Get credentials from environment variables for security\n    db_host = os.environ.get('MYSQL_HOST', '127.0.0.1')\n    db_user = os.environ.get('MYSQL_USER', 'root')\n    db_password = os.environ.get('MYSQL_PASSWORD', 'password')\n    db_name = os.environ.get('MYSQL_DB', 'test_db')\n\n    try:\n        # Establish an asynchronous connection\n        async with await aiomysql.connect(\n            host=db_host,\n            user=db_user,\n            password=db_password,\n            db=db_name,\n            autocommit=True # Or manage transactions manually\n        ) as conn:\n            print(f\"Connected to MySQL on {db_host}\")\n\n            # Create a cursor object\n            async with conn.cursor() as cursor:\n                # Execute a query\n                await cursor.execute(\"SELECT VERSION();\")\n                # Fetch one result\n                version = await cursor.fetchone()\n                print(f\"MySQL Version: {version[0]}\")\n\n                # Execute another query (e.g., create a table)\n                await cursor.execute(\n                    \"CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255));\"\n                )\n                print(\"Table 'users' ensured to exist.\")\n\n                # Insert data\n                await cursor.execute(\"INSERT INTO users (name) VALUES (%s);\", (\"Alice\",))\n                await cursor.execute(\"INSERT INTO users (name) VALUES (%s);\", (\"Bob\",))\n                print(\"Inserted Alice and Bob.\")\n\n                # Select data\n                await cursor.execute(\"SELECT id, name FROM users;\")\n                users = await cursor.fetchall()\n                print(\"Users:\")\n                for user_id, name in users:\n                    print(f\"  ID: {user_id}, Name: {name}\")\n\n            # The connection is automatically closed when exiting the 'async with' block\n\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n\nif __name__ == '__main__':\n    asyncio.run(main())","lang":"python","description":"This quickstart demonstrates how to connect to a MySQL database, create a table, insert data, and fetch results using `aiomysql`. It uses `async with` statements for robust connection and cursor management, ensuring resources are properly closed. Database credentials are retrieved from environment variables for security."},"warnings":[{"fix":"Ensure you `await` the `aiomysql.connect()` call directly, e.g., `conn = await aiomysql.connect(...)`. For older versions, you might need `conn = await asyncio.ensure_future(aiomysql.connect(...))` or similar.","message":"The `aiomysql.connect` function became an `async def` function in version 0.2.0. Previously, it returned a `Future`.","severity":"breaking","affected_versions":"<0.2.0"},{"fix":"Always prepend `await` to calls like `aiomysql.connect()`, `cursor.execute()`, `cursor.fetchone()`, `pool.acquire()`, and `pool.release()`.","message":"Forgetting to `await` asynchronous operations will lead to `RuntimeWarning: coroutine '...' was never awaited` or unexpected behavior.","severity":"gotcha","affected_versions":"All"},{"fix":"For applications with many concurrent database operations, use `await aiomysql.create_pool(...)` to manage a pool of connections. Acquire a connection from the pool with `await pool.acquire()` and release it with `pool.release(conn)` (or use `async with pool.acquire() as conn:`).","message":"Not using connection pooling for high-concurrency applications can lead to performance bottlenecks and resource exhaustion.","severity":"gotcha","affected_versions":"All"},{"fix":"Always use `async with await aiomysql.connect(...) as conn:` and `async with conn.cursor() as cursor:` to ensure connections and cursors are properly closed, even if errors occur.","message":"Improperly closing connections and cursors can lead to resource leaks.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}