跳转至

asmysql v2 API 参考文档

本文档详细说明 asmysql v2 版本的所有 API。

导航

Engine 类

Engine 是 MySQL 连接引擎类,负责管理连接池和执行 SQL 语句。

类定义

class Engine:
    """异步的数据库 aiomysql 封装类"""

类属性(默认值)

属性 类型 默认值 说明
host str "127.0.0.1" MySQL 服务器地址
port int 3306 MySQL 服务器端口
user str "" 用户名
password str "" 密码
charset str "utf8mb4" 字符集
min_pool_size int 1 连接池最小连接数
max_pool_size int 10 连接池最大连接数
pool_recycle float -1 空闲连接回收时间(秒),-1 表示不回收
connect_timeout int 5 连接超时时间(秒)
echo_sql_log bool False 是否打印 SQL 日志
init_sql Optional[str] None 连接初始化时自动执行的 SET SQL(如 MySQL 会话变量)
disconnect_timeout Optional[float] None disconnect 等待连接归还的超时(秒);None 无限等待,有限值超时后强制 terminate

构造函数

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

参数说明:

  • url (str, optional): MySQL 连接 URL,格式:mysql://user:password@host:port/?charset=utf8mb4
  • host (str, optional): MySQL 服务器地址
  • port (int, optional): MySQL 服务器端口
  • user (str, optional): 用户名
  • password (str, optional): 密码
  • charset (str, optional): 字符集
  • min_pool_size (int, optional): 连接池最小连接数
  • max_pool_size (int, optional): 连接池最大连接数
  • pool_recycle (float, optional): 空闲连接回收时间(秒)
  • connect_timeout (int, optional): 连接超时时间(秒)
  • echo_sql_log (bool, optional): 是否打印 SQL 日志
  • init_sql (str, optional): 连接初始化时自动执行的 SET SQL,每条新 TCP 连接首次使用时执行一次
  • disconnect_timeout (float, optional): disconnect 等待超时(秒);None(默认)无限等待,有限值超时后强制 terminate;URL 中 none 表示 None

示例:

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

# 使用关键字参数
engine = Engine(host="127.0.0.1", port=3306, user="root", password="pass", charset="utf8mb4")

方法

connect()

连接到 MySQL,建立 TCP 连接,初始化连接池。连接池固定 autocommit=True(库内置行为,无配置参数);若后端拒绝该握手,内部自动降级为服务端默认并发出警告。如果配置了 init_sql,每条新 TCP 连接首次执行 SQL 时会自动执行初始化 SET SQL。自 v2.4.0 起支持跨事件循环复用:原循环 disconnect 后可在新循环重新 connect(内部锁随循环重建);活池未断开时在新循环 connect 会抛 ConnectionError。

async def connect(self) -> Engine

返回值:返回 self,支持链式调用

示例:

await engine.connect()

disconnect()

等待所有连接释放,并正常关闭 MySQL 连接。默认(disconnect_timeout=None)无限等待;配置有限超时后,超时发出 ResourceWarning 并强制 terminate 全部在用连接;被取消时同样 terminate 并重抛。

async def disconnect(self) -> None

示例:

await engine.disconnect()

terminate()

同步强制清理连接池(幂等,自 v2.5.0)。不等待连接归还,立即关闭全部在用连接并掐断在途查询,best-effort 清理空闲连接;适用 atexit、同步 shutdown 钩子。与 disconnect() 的对照:terminate=同步强制,disconnect=async 优雅等待。

def terminate(self) -> None

调用后 is_connected 为 False,execute() 抛 ConnectionError;可重新 connect() 复用。未 connect 时调用为 no-op;显式调用不发警告。

示例:

import atexit

atexit.register(engine.terminate)  # 同步钩子,无需事件循环

release_connections()

释放连接池中所有空闲的连接。

async def release_connections(self) -> None

示例:

await engine.release_connections()

execute()

执行 SQL 语句并返回 Result 对象。

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]]

参数说明:

  • query (str): SQL 语句
  • values (Union[Sequence, dict], optional): 参数,可以是元组或字典
  • stream (bool, optional): 是否流式返回结果,默认使用 self.stream
  • result_class (type, optional): 结果类型,默认 tuple

返回值:返回 Result 对象,支持以下用法:

  1. async with engine.execute(...) as result:
  2. async for item in engine.execute(...):

示例:

# 方式一:上下文管理器
async with engine.execute("SELECT * FROM users WHERE id = %s", (1,)) as result:
    data = await result.fetch_one()

# 方式二:上下文管理器 + fetch_all
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)

execute_many()

批量执行 SQL 语句并返回 Result 对象。空参数列表([])时不获取连接、不执行 SQL,发出 UserWarning 且 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]]

参数说明:

  • query (str): SQL 语句
  • values (Sequence[Union[Sequence, dict]]): 参数列表,每个元素可以是元组或字典
  • stream (bool, optional): 是否流式返回结果
  • result_class (type, optional): 结果类型

返回值:返回 Result 对象

示例:

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"插入了 {result.row_count} 条记录")

属性

status

返回数据库连接池状态。

@property
def status(self) -> EngineStatus

返回值:EngineStatus 字典,包含以下字段:

  • address (str): 连接地址
  • connected (bool): 是否已连接
  • pool_minsize (Optional[int]): 连接池最小大小
  • pool_maxsize (Optional[int]): 连接池最大大小
  • pool_size (Optional[int]): 连接池当前大小
  • pool_free (Optional[int]): 空闲连接数
  • pool_used (Optional[int]): 使用中连接数

示例:

status = engine.status
print(f"连接状态: {status['connected']}")
print(f"连接池大小: {status['pool_size']}")

is_connected

数据库是否已连接。

@property
def is_connected(self) -> bool

返回值:bool,已连接返回 True,否则返回 False

示例:

if engine.is_connected:
    print("已连接")

pool

获取连接池对象(内部使用)。

@property
def pool(self) -> Pool

返回值:aiomysql.Pool 对象

注意:此属性仅供内部使用,如果未连接会抛出 ConnectionError

url

连接 URL(只读)。

url: Final[str]

示例:

print(engine.url)  # mysql://127.0.0.1:3306/

特殊方法

aenter() / aexit()

支持 async with 语法。

async def __aenter__(self) -> Engine
async def __aexit__(self, exc_type, exc_value, exc_tb) -> None

示例:

async with engine:
    async with engine.execute("SELECT * FROM users") as result:
        data = await result.fetch_all()

await()

支持 await engine 语法。

def __await__(self) -> Generator[Any, None, Engine]

示例:

await engine  # 等同于 await engine.connect()

call()

支持 await engine() 语法。

async def __call__(self) -> Engine

示例:

await engine()  # 等同于 await engine.connect()

del()

GC 时的安全网(自 v2.5.0):Engine 未被 disconnect() 即被回收时,发出 ResourceWarning 并调用 terminate() 同步清理。disconnect()/terminate() 后或从未 connect 时静默;不 await、不复活引用。生产仍应显式 await engine.disconnect()。

AsMysql 类

AsMysql 是业务逻辑开发的基类,用于封装业务方法。

类定义

class AsMysql:
    """Mysql 编写业务逻辑的类"""

构造函数

def __init__(self, engine: Engine) -> None

参数说明:

  • engine (Engine): Engine 实例

示例:

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


class UserService(AsMysql):
    pass


service = UserService(engine)

构造式单例

AsMysql 通过 __new__ 实现进程内构造式单例:以 (子类, 引擎对象) 为键复用实例。

def __new__(cls, engine: Engine) -> AsMysql
  • 同一子类 + 同一引擎对象:返回同一实例;命中复用后 __init__ 会再次执行,但只是重新赋值同一个引擎
  • 不同引擎对象:各持专属实例
  • 不同子类 + 同一引擎对象:各自独立,互不串扰
  • 实例表为强引用缓存,需配合 release() 注销

示例:

class UserService(AsMysql):
    pass


assert UserService(engine) is UserService(engine)

类方法 release

注销实例表条目(只解除强引用,不负责 disconnect)。

@classmethod
def release(cls, engine: Engine | None = None) -> int

参数说明:

  • engine (Engine, optional): 指定引擎时,删除该引擎在所有子类下的条目;不传时清空全表

返回值:删除的条目数(int)

示例:

removed = UserService.release(engine)  # 删除该引擎相关条目
removed = UserService.release()  # 清空全表(lifespan shutdown)

生命周期与 GC 语义:

  • 实例表强引用实例,__del__ 不会触发,实例不会因垃圾回收自动注销
  • 确定性清理使用 release();引擎断开(is_connected 为 False)的旧条目在下一次未命中构造时惰性剔除
  • release() 不调用 disconnect(),连接池仍由 engine.disconnect() 关闭
  • 推荐 shutdown 顺序:await engine.disconnect() → release(engine)(顺序可互换)

属性

client

访问 Engine 实例。

@property
def client(self) -> Engine

返回值:Engine 实例

示例:

class UserService(AsMysql):
    async def get_users(self):
        async with self.client.execute("SELECT * FROM users") as result:
            return await result.fetch_all()

Result 类

Result 是 SQL 执行结果的封装类,提供数据获取和错误处理功能。

类定义

class Result(Generic[T]):
    """SQL 执行结果类"""

构造函数

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

参数说明(内部使用,通常不需要直接构造):

  • pool (Pool): 连接池对象(实例属性 result.pool 类型为 Optional[Pool],close/自动释放后清空为 None)
  • query (str): SQL 语句
  • values (Union[Sequence, dict], optional): 参数
  • execute_many (bool): 是否批量执行
  • stream (bool): 是否流式返回
  • result_class (type): 结果类型
  • init_sql (str, optional): 连接初始化时自动执行的 SET SQL

方法

fetch_one()

获取一条记录。

async def fetch_one(self) -> Optional[T]

返回值:返回一条记录,如果没有数据则返回 None

使用约束:必须在 async with / async for 上下文内使用,或与显式 close() 配对;不推荐裸执行后 fetch 且不 close(触发 GC 丢弃安全网,见 __del__())。

示例:

async with engine.execute("SELECT * FROM users WHERE id = %s", (1,)) as result:
    user = await result.fetch_one()
    if user:
        print(user)

fetch_many()

获取多条记录。

async def fetch_many(self, size: int = None) -> list[T]

参数说明:

  • size (int, optional): 获取记录的数量,默认获取所有可用记录

返回值:返回记录列表

使用约束:必须在 async with / async for 上下文内使用,或与显式 close() 配对;不推荐裸执行后 fetch 且不 close(触发 GC 丢弃安全网,见 __del__())。

示例:

async with engine.execute("SELECT * FROM users") as result:
    users = await result.fetch_many(10)  # 获取 10 条记录

fetch_all()

获取所有记录。

async def fetch_all(self) -> list[T]

返回值:返回所有记录的列表

注意:此方法会自动关闭游标连接

示例:

async with engine.execute("SELECT * FROM users") as result:
    all_users = await result.fetch_all()

iterate()

异步生成器,遍历所有记录。

async def iterate(self) -> AsyncGenerator[T, None]

返回值:异步生成器,逐行返回记录

注意:此方法会自动关闭游标连接

示例:

async with engine.execute("SELECT * FROM users") as result:
    async for user in result.iterate():
        print(user)

close()

关闭游标并释放连接。可安全重复调用;关闭后 result.pool 清空为 None(自 v2.5.0,缓存已关闭 Result 不再钉住 Pool 与事件循环)。未执行的 Result 先 close 后再执行抛 RuntimeError。

async def close(self) -> None

示例:

async with engine.execute("SELECT * FROM users") as result:
    data = await result.fetch_one()
    # ... 其他操作
# 退出 async with 时自动关闭

属性

error

错误异常对象。

@property
def error(self) -> Optional[MySQLError]

返回值:MySQLError 异常对象,如果没有错误则返回 None

自 v2.4.0 起,该异常对象的 __traceback__ 为 None(断开帧链防内存驻留);排查请使用 error_no / error_msg。

示例:

async with engine.execute("SELECT * FROM invalid_table") as result:
    if result.error:
        print(f"错误: {result.error}")

error_no

错误码。

@property
def error_no(self) -> int

返回值:错误码(整数),如果没有错误则返回 0

示例:

if result.error:
    print(f"错误码: {result.error_no}")

error_msg

错误信息。

@property
def error_msg(self) -> str

返回值:错误信息(字符串),如果没有错误则返回空字符串

示例:

if result.error:
    print(f"错误信息: {result.error_msg}")

row_count

受影响的行数。

@property
def row_count(self) -> Optional[int]

返回值: - 受影响的行数(整数) - 如果发生错误,返回 None - 如果使用流式查询(stream=True),返回 None

示例:

async with engine.execute("INSERT INTO users (name) VALUES (%s)", ("张三",)) as result:
    print(f"插入了 {result.row_count} 条记录")

last_rowid

最近插入的记录的 ID。

@property
def last_rowid(self) -> Optional[int]

返回值: - 最近插入的记录的 ID(整数) - 如果没有插入数据或发生错误,返回 None

示例:

async with engine.execute("INSERT INTO users (name) VALUES (%s)", ("张三",)) as result:
    print(f"新插入的 ID: {result.last_rowid}")

row_number

当前游标的位置。

@property
def row_number(self) -> Optional[int]

返回值: - 当前游标在结果集中的行索引(从 0 开始) - 如果无法确定索引或发生错误,返回 None

示例:

async with engine.execute("SELECT * FROM users") as result:
    row = await result.fetch_one()
    while row:
        print(f"当前位置: {result.row_number}")
        row = await result.fetch_one()

特殊方法

aenter() / aexit()

支持 async with 语法。

async def __aenter__(self) -> Result[T]
async def __aexit__(self, exc_type, exc_value, exc_tb) -> None

示例:

async with engine.execute("SELECT * FROM users") as result:
    data = await result.fetch_all()

aiter() / anext()

支持 async for 语法。

def __aiter__(self) -> Result[T]
async def __anext__(self) -> T

示例:

async with engine.execute("SELECT * FROM users") as result:
    async for user in result:
        print(user)

await()

未实现:Result 不支持 await result 语法(抛 TypeError)。这是刻意的设计决策,避免泄漏成为默认用法。

标准形式:

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()

内部执行入口:由 __aenter__ / __aiter__ / __anext__ 自动调用,完成连接获取与 SQL 执行(幂等,仅执行一次)。

async def __call__(self) -> Result[T]

不推荐单独使用:裸执行(await result())后必须经 async with 或显式 close() 释放连接,否则 GC 时连接被丢弃(不复用)并发 ResourceWarning(自 v2.6.0)。

示例(标准形式):

result = engine.execute("SELECT * FROM users")
async with result:
    data = await result.fetch_all()

del()

GC 安全网(自 v2.6.0):已执行的 Result 未被正确关闭即被回收时,同步丢弃连接(关 transport,不发 COM_QUIT)并经 pool.release() 完成池记账,发出 ResourceWarning。连接不回池复用;未提交事务由服务端回滚,已自动提交的数据不受影响;disconnect() 不再因此永久挂死。已关闭或未执行时静默;不 await、不复活引用。生产必须使用 async with / async for / close(),安全网仅作兜底。

类型定义

EngineStatus

连接引擎状态类型。

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]

类型别名

AsyncEngine = Engine
AsyncResult = Result

这些类型别名用于向后兼容或类型提示。

导入方式

# 方式一:从主模块导入
from asmysql import Engine, AsMysql, Result

# 方式二:从 v2 子模块导入
from asmysql.v2 import Engine, AsMysql, Result

# 方式三:使用类型别名
from asmysql import AsyncEngine, AsyncResult