asmysql v2 API Reference¶
This document details all APIs in asmysql v2 version.
Navigation¶
Engine Class¶
Engine is the MySQL connection engine class, responsible for managing connection pool and executing SQL statements.
Class Definition¶
Class Attributes (Default Values)¶
| Attribute | 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 |
Optional[str] |
None |
SET SQL to auto-execute on each new TCP connection's first use (e.g. MySQL session variables) |
disconnect_timeout |
Optional[float] |
None |
Timeout (seconds) for disconnect waiting connections to return; None waits forever, a finite value forces terminate on timeout |
Constructor¶
def __init__(
self,
url: str = None,
*,
host: str = None,
port: int = None,
user: str = None,
password: str = None,
charset: str = None,
min_pool_size: int = None,
max_pool_size: int = None,
pool_recycle: float = None,
connect_timeout: int = None,
echo_sql_log: bool = None,
init_sql: str = None,
disconnect_timeout: float = None,
) -> None
Parameter Description:
url(str, optional): MySQL connection URL, format:mysql://user:password@host:port/?charset=utf8mb4host(str, optional): MySQL server addressport(int, optional): MySQL server portuser(str, optional): Usernamepassword(str, optional): Passwordcharset(str, optional): Character setmin_pool_size(int, optional): Minimum connection pool sizemax_pool_size(int, optional): Maximum connection pool sizepool_recycle(float, optional): Idle connection recycle time (seconds)connect_timeout(int, optional): Connection timeout (seconds)echo_sql_log(bool, optional): Whether to print SQL logsinit_sql(str, optional): SET SQL to auto-execute on connection init, executed once per new TCP connection on first usedisconnect_timeout(float, optional): disconnect wait timeout (seconds); None (default) waits forever, a finite value forces terminate on timeout;nonein URL means None
Examples:
# Using URL
engine = Engine(url="mysql://root:pass@127.0.0.1:3306/?charset=utf8mb4")
# Using keyword arguments
engine = Engine(host="127.0.0.1", port=3306, user="root", password="pass", charset="utf8mb4")
Methods¶
connect()¶
Connect to MySQL, establish TCP connection, initialize connection pool. The pool is fixed at autocommit=True (built-in library behavior, no configuration parameter); if a backend rejects the handshake, the library internally falls back to the server default and emits a warning. If init_sql is configured, each new TCP connection will automatically execute the init SQL on first use. Since v2.4.0, reuse across event loops is supported: after disconnecting in the original loop, you can connect again in a new loop (the internal lock is rebuilt per loop); connecting in a new loop while the pool is still alive raises ConnectionError.
Return Value: Returns self, supports chaining
Example:
disconnect()¶
Wait for all connections to be released and properly close MySQL connection. By default (disconnect_timeout=None) waits forever; with a finite timeout configured, emits a ResourceWarning on timeout and forcibly terminates all in-use connections; on cancellation also terminates and re-raises.
Example:
terminate()¶
Synchronously force-clean the connection pool (idempotent, since v2.5.0). Does not wait for connections to return: immediately closes all in-use connections and severs in-flight queries, then cleans up idle connections best-effort; suitable for atexit and synchronous shutdown hooks. Contrast with disconnect(): terminate = synchronous and forceful, disconnect = async graceful wait.
After the call, is_connected is False and execute() raises ConnectionError; you can connect() again to reuse the Engine. A no-op when called before connect; explicit calls emit no warning.
Example:
release_connections()¶
Release all idle connections in the connection pool.
Example:
execute()¶
Execute SQL statement and return Result object.
def execute(
self,
query: str,
values: Union[Sequence, dict] = None,
*,
stream: bool = None,
result_class: type[T] = None,
) -> Union[AsyncContextManager[Result[T]], AsyncGenerator[T, None]]
Parameter Description:
query(str): SQL statementvalues(Union[Sequence, dict], optional): Parameters, can be tuple or dictstream(bool, optional): Whether to stream results, defaults toself.streamresult_class(type, optional): Result type, defaults totuple
Return Value: Returns Result object, supports the following usages:
async with engine.execute(...) as result:async for item in engine.execute(...):
Examples:
# Method 1: context manager
async with engine.execute("SELECT * FROM users WHERE id = %s", (1,)) as result:
data = await result.fetch_one()
# Method 2: context manager + fetch_all
async with engine.execute("SELECT * FROM users") as result:
data = await result.fetch_all()
# Method 3: direct iteration
async for row in engine.execute("SELECT * FROM users"):
print(row)
execute_many()¶
Batch execute SQL statements and return Result object. With an empty parameter list ([]), no connection is acquired and no SQL is executed; a UserWarning is emitted and row_count=0.
def execute_many(
self,
query: str,
values: Sequence[Union[Sequence, dict]],
*,
stream: bool = None,
result_class: type[T] = None,
) -> Union[AsyncContextManager[Result[T]], AsyncGenerator[T, None]]
Parameter Description:
query(str): SQL statementvalues(Sequence[Union[Sequence, dict]]): Parameter list, each element can be tuple or dictstream(bool, optional): Whether to stream resultsresult_class(type, optional): Result type
Return Value: Returns Result object
Example:
data = [("张三", "zhangsan@example.com"), ("李四", "lisi@example.com")]
async with engine.execute_many("INSERT INTO users (name, email) VALUES (%s, %s)", data) as result:
print(f"Inserted {result.row_count} records")
Attributes¶
status¶
Returns database connection pool status.
Return Value: EngineStatus dictionary, contains the following fields:
address(str): Connection addressconnected(bool): Whether connectedpool_minsize(Optional[int]): Connection pool minimum sizepool_maxsize(Optional[int]): Connection pool maximum sizepool_size(Optional[int]): Connection pool current sizepool_free(Optional[int]): Number of idle connectionspool_used(Optional[int]): Number of connections in use
Example:
status = engine.status
print(f"Connection status: {status['connected']}")
print(f"Pool size: {status['pool_size']}")
is_connected¶
Whether the database is connected.
Return Value: bool, returns True if connected, otherwise False
Example:
pool¶
Get connection pool object (internal use).
Return Value: aiomysql.Pool object
Note: This attribute is for internal use only, will raise ConnectionError if not connected
url¶
Connection URL (read-only).
Example:
Special Methods¶
aenter() / aexit()¶
Support for async with syntax.
Example:
async with engine:
async with engine.execute("SELECT * FROM users") as result:
data = await result.fetch_all()
await()¶
Support for await engine syntax.
Example:
call()¶
Support for await engine() syntax.
Example:
del()¶
GC safety net (since v2.5.0): if the Engine is reclaimed without being disconnect()ed, emits a ResourceWarning and calls terminate() for synchronous cleanup. Silent after disconnect()/terminate() or when never connected; never awaits and never resurrects references. Production code should still explicitly await engine.disconnect().
AsMysql Class¶
AsMysql is the base class for business logic development, used to encapsulate business methods.
Class Definition¶
Constructor¶
Parameter Description:
engine(Engine):Engineinstance
Example:
engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")
await engine.connect()
class UserService(AsMysql):
pass
service = UserService(engine)
Constructive Singleton¶
AsMysql implements a process-wide constructive singleton through __new__: instances are reused with (subclass, engine object) as the key.
- Same subclass + same engine object: returns the same instance; after a hit,
__init__runs again but only reassigns the same engine - Different engine objects: each keeps its own instance
- Different subclasses + same engine object: independent and isolated
- The instance table is a strong-reference cache and must be unregistered with
release()
Example:
Class Method release¶
Unregisters instance table entries (only releases strong references, does not call disconnect).
Parameter Description:
engine(Engine, optional): when given, removes this engine's entries across all subclasses; when omitted, clears the whole table
Return Value: number of removed entries (int)
Example:
removed = UserService.release(engine) # Remove entries for this engine
removed = UserService.release() # Clear the whole table (lifespan shutdown)
Lifecycle and GC Semantics:
- The instance table holds strong references to instances, so
__del__never triggers and instances are never unregistered by garbage collection - Deterministic cleanup uses
release(); stale entries of disconnected engines (is_connectedisFalse) are lazily removed on the next construction miss release()does not calldisconnect(); the connection pool is still closed byengine.disconnect()- Recommended shutdown order:
await engine.disconnect()→release(engine)(order can be swapped)
Attributes¶
client¶
Access Engine instance.
Return Value: Engine instance
Example:
class UserService(AsMysql):
async def get_users(self):
async with self.client.execute("SELECT * FROM users") as result:
return await result.fetch_all()
Result Class¶
Result is the encapsulation class for SQL execution results, providing data retrieval and error handling functionality.
Class Definition¶
Constructor¶
def __init__(
self,
*,
pool: Pool,
query: str,
values: Union[Sequence, dict] = None,
execute_many: bool = False,
stream: bool = False,
result_class: T = tuple,
init_sql: str = None,
) -> None
Parameter Description (internal use, usually no need to construct directly):
pool(Pool): Connection pool object (the instance attributeresult.poolis typedOptional[Pool]and cleared toNoneafter close/auto-release)query(str): SQL statementvalues(Union[Sequence, dict], optional): Parametersexecute_many(bool): Whether batch executionstream(bool): Whether streaming resultresult_class(type): Result typeinit_sql(str, optional): SET SQL to auto-execute on connection init
Methods¶
fetch_one()¶
Get a single record.
Return Value: Returns a single record, returns None if no data
Usage Constraint: must be used inside an async with / async for context, or paired with an explicit close(); bare execution + fetch without close is not recommended (triggers the GC discard safety net, see __del__()).
Example:
async with engine.execute("SELECT * FROM users WHERE id = %s", (1,)) as result:
user = await result.fetch_one()
if user:
print(user)
fetch_many()¶
Get multiple records.
Parameter Description:
size(int, optional): Number of records to fetch, defaults to all available records
Return Value: Returns list of records
Usage Constraint: must be used inside an async with / async for context, or paired with an explicit close(); bare execution + fetch without close is not recommended (triggers the GC discard safety net, see __del__()).
Example:
async with engine.execute("SELECT * FROM users") as result:
users = await result.fetch_many(10) # Get 10 records
fetch_all()¶
Get all records.
Return Value: Returns list of all records
Note: This method will automatically close cursor connection
Example:
iterate()¶
Async generator, iterate through all records.
Return Value: Async generator, returns records row by row
Note: This method will automatically close cursor connection
Example:
async with engine.execute("SELECT * FROM users") as result:
async for user in result.iterate():
print(user)
close()¶
Close cursor and release connection. Safe to call repeatedly; after close, result.pool is cleared to None (since v2.5.0, caching closed Results no longer pins the Pool and the event loop). Executing an unexecuted Result after close raises RuntimeError.
Example:
async with engine.execute("SELECT * FROM users") as result:
data = await result.fetch_one()
# ... other operations
# Automatically closed on exiting async with
Attributes¶
error¶
Error exception object.
Return Value: MySQLError exception object, returns None if no error
Since v2.4.0, the exception's
__traceback__isNone(frame chain severed to prevent memory retention); useerror_no/error_msgfor troubleshooting.
Example:
async with engine.execute("SELECT * FROM invalid_table") as result:
if result.error:
print(f"Error: {result.error}")
error_no¶
Error code.
Return Value: Error code (integer), returns 0 if no error
Example:
error_msg¶
Error message.
Return Value: Error message (string), returns empty string if no error
Example:
row_count¶
Number of affected rows.
Return Value:
- Number of affected rows (integer)
- Returns None if error occurs
- Returns None if using streaming query (stream=True)
Example:
async with engine.execute("INSERT INTO users (name) VALUES (%s)", ("张三",)) as result:
print(f"Inserted {result.row_count} records")
last_rowid¶
ID of the most recently inserted record.
Return Value:
- ID of the most recently inserted record (integer)
- Returns None if no data inserted or error occurs
Example:
async with engine.execute("INSERT INTO users (name) VALUES (%s)", ("张三",)) as result:
print(f"Newly inserted ID: {result.last_rowid}")
row_number¶
Current cursor position.
Return Value:
- Current cursor row index in result set (0-based)
- Returns None if index cannot be determined or error occurs
Example:
async with engine.execute("SELECT * FROM users") as result:
row = await result.fetch_one()
while row:
print(f"Current position: {result.row_number}")
row = await result.fetch_one()
Special Methods¶
aenter() / aexit()¶
Support for async with syntax.
async def __aenter__(self) -> Result[T]
async def __aexit__(self, exc_type, exc_value, exc_tb) -> None
Example:
aiter() / anext()¶
Support for async for syntax.
Example:
await()¶
Not implemented: Result does not support await result syntax (raises TypeError). This is a deliberate design decision to avoid leaks becoming the default usage.
Standard forms:
async with engine.execute("SELECT * FROM users") as result:
data = await result.fetch_all()
async for row in engine.execute("SELECT * FROM users"):
print(row)
call()¶
Internal execution entry: called automatically by __aenter__ / __aiter__ / __anext__ to acquire a connection and execute the SQL (idempotent, executes only once).
Standalone use not recommended: after bare execution (await result()), the connection must be released via async with or an explicit close(); otherwise the connection is discarded (not reused) at GC with a ResourceWarning (since v2.6.0).
Example (standard form):
del()¶
GC safety net (since v2.6.0): if an executed Result is reclaimed without being properly closed, synchronously discards the connection (closes the transport without sending COM_QUIT) and completes pool bookkeeping via pool.release(), emitting a ResourceWarning. The connection is not returned to the pool for reuse; uncommitted transactions are rolled back by the server and already auto-committed data is unaffected; disconnect() no longer hangs forever because of this. Silent when already closed or never executed; never awaits and never resurrects references. Production code must use async with / async for / close(); the safety net is only a fallback.
Type Definitions¶
EngineStatus¶
Connection engine status type.
class EngineStatus(TypedDict):
address: str
connected: bool
pool_minsize: Optional[int]
pool_maxsize: Optional[int]
pool_size: Optional[int]
pool_free: Optional[int]
pool_used: Optional[int]
Type Aliases¶
These type aliases are used for backward compatibility or type hints.