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. ClickHouse SET) |
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,
) -> 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 use
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. If init_sql is configured, each new TCP connection will automatically execute the init SQL on first use.
Return Value: Returns self, supports chaining
Example:
disconnect()¶
Wait for all connections to be released and properly close MySQL connection.
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.
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:
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)
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 objectquery(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
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
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.
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
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()¶
Support for await result syntax.
Example:
call()¶
Support for await result() syntax.
Example:
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.