用途:aiomysql 为 Python 提供 asyncio 原生的 MySQL 访问,基于 PyMySQL 封装,暴露 Connection、Cursor 与 Pool 等异步原语,对应同步 DBAPI 接口。适用于异步服务中长期连接 MySQL 的场景。
安装与要求:Python 3.9+、PyMySQL。安装:pip install aiomysql;如需 SQLAlchemy 表达式层:pip install aiomysql sqlalchemy。
主要能力:连接池(create_pool)、异步上下文管理器(async with)、参数化查询、多种游标(默认 Cursor、aiomysql.DictCursor、SSCursor、SSDictCursor)、显式事务(begin/commit/rollback)、分页获取(fetchone/fetchall/fetchmany)、lastrowid 与 rowcount、单连接 connect(),以及 aiomysql.sa(create_engine)的 SQLAlchemy 表达式支持。
必要用法与原则:生产环境始终使用连接池,不用裸 connect();用 async with 保证连接与游标释放;参数作为 execute() 第二个参数传入,禁止手工拼接 SQL;autocommit 默认 False,需显式 commit;关闭时先 pool.close() 再 await pool.wait_closed();pool_recycle 应小于 MySQL 的 wait_timeout;大结果集用 fetchmany(size=N) 或 SSCursor 而非 fetchall();cur.close() 是协程,须 await;Python 3.10+ 不再传 loop 参数。
限制:以上内容源自资料,未提供收费、价格、平台与效果信息;其他细节暂未提供。