Skip to content

Connection Management

Connection Configuration

Using URL Connection String

from asmysql import Engine

# Basic URL
engine = Engine(url="mysql://root:pass@127.0.0.1:3306/?charset=utf8mb4")

# Complete URL (with all parameters)
engine = Engine(
    url="mysql://root:pass@127.0.0.1:3306/"
    "?charset=utf8mb4"
    "&min_pool_size=2"
    "&max_pool_size=20"
    "&pool_recycle=3600"
    "&connect_timeout=10"
    "&echo_sql_log=false"
)

Using Keyword Arguments

from asmysql import Engine

engine = Engine(
    host="127.0.0.1",
    port=3306,
    user="root",
    password="pass",
    charset="utf8mb4",
    min_pool_size=1,
    max_pool_size=10,
    pool_recycle=-1,
    connect_timeout=5,
    echo_sql_log=False,
    init_sql=None,  # Optional: SET SQL to auto-execute on connection init
    disconnect_timeout=None,  # Optional: disconnect wait timeout (seconds), None waits forever
)

Connection Parameters

Parameter Type Default Description
host str "127.0.0.1" MySQL server address
port int 3306 MySQL server port
user str "" Username
password str "" Password
charset str "utf8mb4" Character set
min_pool_size int 1 Minimum connection pool size
max_pool_size int 10 Maximum connection pool size
pool_recycle float -1 Idle connection recycle time (seconds), -1 means no recycle
connect_timeout int 5 Connection timeout (seconds)
echo_sql_log bool False Whether to print SQL logs
init_sql str None SET SQL to auto-execute on each new TCP connection's first use
disconnect_timeout float | None None Timeout (seconds) for disconnect waiting connections to return; None waits forever, a finite value forces terminate on timeout; none in URL means None

Connect and Disconnect

Method 1: Explicit Connection

from asmysql import Engine

engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")

# Connect
await engine.connect()
# ... use engine
await engine.disconnect()

Method 2: Using Context Manager

from asmysql import Engine

engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")

async with engine:
    # ... use engine
    pass  # Automatically disconnect

Method 3: Using await

from asmysql import Engine

engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")

await engine()  # Equivalent to await engine.connect()

Check Connection Status

from asmysql import Engine

engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")

# Check if connected
if engine.is_connected:
    print("Connected")

# Get connection status information
await engine.connect()
status = engine.status
print(f"Address: {status['address']}")
print(f"Connected: {status['connected']}")
print(f"Pool size: {status['pool_size']}")
print(f"Free connections: {status['pool_free']}")
print(f"Used connections: {status['pool_used']}")

Release Connections

# Release all idle connections in the pool
await engine.release_connections()

Disconnect Wait Policy (disconnect_timeout)

disconnect() must wait for all connections to return (unclosed Result objects still hold connections):

  • None (default): waits forever, consistent with legacy behavior; make sure all Result objects are closed;
  • Finite value (e.g. 0.5): after the graceful wait times out, emits a ResourceWarning and forcibly terminates all in-use connections, guaranteed to converge; in-flight queries receive error_no=2013;
  • <= 0: no wait, terminate immediately.
# When convergence guarantees are needed, configure explicitly based on the longest business execution time
engine = Engine(url="mysql://root:pass@127.0.0.1:3306/", disconnect_timeout=30)

Synchronous Forced Cleanup: terminate()

terminate() is a synchronous forced cleanup method (since v2.5.0), complementary to the async graceful disconnect():

Method Semantics Typical scenarios
await disconnect() Gracefully waits for all connections to return (see disconnect_timeout) Normal shutdown inside an event loop
terminate() Synchronous and forceful: no waiting for returns, immediately closes all in-use connections and severs in-flight queries atexit, synchronous shutdown hooks, fallback cleanup
import atexit

engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")
atexit.register(engine.terminate)  # synchronous hook, no event loop required

Behavior notes:

  • Idempotent; a no-op when called before connect; explicit calls emit no warning;
  • After the call, is_connected is False and execute() raises ConnectionError; you can connect() again to reuse the Engine;
  • In-use connections are closed immediately (aiomysql Pool.terminate()); a late result.close() is safe; in-flight queries receive a connection-lost error;
  • Idle connections are cleaned up best-effort: this relies on the aiomysql private attribute _free and defensively degrades to terminate-only when it is missing or changes shape; when the event loop is already closed, per-connection close exceptions are isolated and never propagate.

__del__ safety net: if an Engine is garbage-collected without being disconnect()ed, it automatically emits a ResourceWarning and calls terminate() for synchronous cleanup, instead of relying on Connection.__del__ (warning noise, delayed cyclic GC, RuntimeError when the loop is already closed). GC is silent after disconnect()/terminate() or when never connected. Production code should still explicitly await engine.disconnect(); the safety net is only a fallback.

Reuse Across Event Loops

An Engine can be reused across multiple event loops (e.g. multiple asyncio.run() calls), but must follow the "disconnect in the original loop → connect in the new loop" pattern:

engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")


async def job():
    await engine.connect()
    async with engine.execute("SELECT 1") as result:
        print(await result.fetch_one())
    await engine.disconnect()


asyncio.run(job())  # Event loop 1
asyncio.run(job())  # Event loop 2: the internal lock is rebuilt and the pool is recreated

Constraints:

  • An aiomysql pool is bound to its event loop at creation time; a live pool cannot be shared across loops: with the pool still connected, calling connect(), accessing engine.pool, or calling execute() in a new loop raises a ConnectionError with a clear message;
  • An abandoned Engine whose loop has closed without disconnecting is not guaranteed to be cleanable in a new loop; always disconnect within the original loop;
  • Concurrent connect() calls within the same loop are still serialized by the internal lock; behavior is unchanged.

Connection Init SQL (init_sql)

The init_sql parameter automatically executes preset SQL on each new TCP connection's first use. Ideal for setting session-level variables, such as MySQL session variables (time_zone, sql_mode, and other settings without query-level syntax). For ClickHouse async inserts, the query-level SETTINGS clause is recommended instead (see below).

How It Works

  • init_sql execution is implemented in Result.__call__(), not at connect() stage
  • Uses weakref.WeakKeyDictionary with Pool as key and a WeakSet tracking initialized connections by object identity (no id-based tracking, avoiding address reuse)
  • Executes on an independent buffered cursor that is closed immediately, without affecting streaming business cursors
  • Executes init_sql on first SQL execution of a new connection; skips on subsequent reuses
  • When a connection is recycled via pool_recycle, the new connection re-executes init_sql
  • If init_sql fails: the main SQL is not executed, the error is written to result.error, and the connection is discarded instead of reused
  • Modifying autocommit in init_sql is not recommended; if required, the client falls back to commit/rollback based on server transaction state — functionally correct, but the semantics are your responsibility

ClickHouse Async Insert Configuration

Recommended: query-level SETTINGS clause (zero extra round-trips, no session state, execute_many compatible):

from asmysql import Engine

engine = Engine(host="192.168.62.195", port=9004, user="default", password="")
await engine.connect()

# wait_for_async_insert=1: waits for the async flush to complete, failures are visible; do not use 0 (fire-and-forget cannot guarantee persistence)
async with engine.execute(
    "INSERT INTO audit_log SETTINGS async_insert=1, wait_for_async_insert=1 VALUES (%s, %s)",
    ("event", "payload"),
) as result:
    pass

Optional alternative: init_sql session-level settings (executed once per new connection):

from asmysql import Engine

engine = Engine(
    host="192.168.62.195",
    port=9004,
    user="default",
    password="",
    init_sql="SET async_insert = 1, wait_for_async_insert = 1",
)
await engine.connect()

# All subsequent execute() calls automatically run SET on new connections
async with engine.execute("INSERT INTO audit_log ...") as result:
    pass

MySQL Session Variables

from asmysql import Engine

engine = Engine(
    url="mysql://root:pass@127.0.0.1:3306/",
    init_sql="SET SESSION wait_timeout = 600, SESSION interactive_timeout = 600",
)
await engine.connect()