Hopsworks Async MySQL Driver (aiomysql)

0.2.2 · active · verified Thu Apr 16

The `hopsworks-aiomysql` library provides an asynchronous MySQL client for Python, distributed by Logical Clocks, primarily for use within the Hopsworks ecosystem. It is effectively a distribution of the popular `aiomysql` library (currently version 0.2.2) and follows its API. It's actively maintained but release cadence is tied to Hopsworks platform updates rather than independent `aiomysql` releases.

Common errors

Warnings

Install

Imports

Quickstart

Establishes a connection pool to a MySQL database using environment variables for credentials, executes a simple query, and properly closes the pool. This example showcases the `async with` context managers for connections and cursors.

import asyncio
import os
from aiomysql import create_pool

async def main():
    # Database connection details, preferably from environment variables
    pool = await create_pool(
        host=os.environ.get('MYSQL_HOST', '127.0.0.1'),
        port=int(os.environ.get('MYSQL_PORT', '3306')),
        user=os.environ.get('MYSQL_USER', 'root'),
        password=os.environ.get('MYSQL_PASSWORD', 'password'),
        db=os.environ.get('MYSQL_DB', 'test_db'),
        autocommit=True,
        minsize=1,
        maxsize=5
    )
    print("Connection pool created.")

    async with pool.acquire() as conn:
        # 'conn' is an aiomysql.connection.Connection object
        async with conn.cursor() as cur:
            # 'cur' is an aiomysql.cursors.Cursor object
            await cur.execute("SELECT 1+1;")
            (result,) = await cur.fetchone()
            print(f"Query result: {result}")
    
    # Ensure the pool is closed gracefully
    pool.close()
    await pool.wait_closed()
    print("Connection pool closed.")

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

view raw JSON →