aiomysql的官网文档为:https://aiomysql.readthedocs.io/en/latest/index.html
什么是aiomysql
aimysql是从asyncio(PEP-3156/tulip)框架访问MySQL数据库的“驱动程序”。它依赖并重用PyMySQL的大部分部分。aiomysql试图成为一个很棒的aiopg库,并保留相同的api、外观和感觉。
说人话就是:aiomysql依赖于我们熟悉的pymysql库同时它支持异步框架下(结合asyncio)使用。
安装:
pip3 install aiomysql
aiomysql基本用法:
在平时使用pymysql时,调用conn.f()的地方,改写成await conn.f()即可。
一:单例的用法:
import asyncio
import aiomysql
async def test_example(loop):
conn = await aiomysql.connect(host='127.0.0.1', port=3306,
user='root', password='123456', db='test',
loop=loop)
cur = await conn.cursor()
await cur.execute("SELECT * FROM test_biao")
print(cur.description)
r = await cur.fetchall()
print(r)
await cur.close()
conn.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(test_example(loop))
二:连接池的用法:
import asyncio
import aiomysql
async def test_example(loop):
pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
user='root', password='123456',
db='test', loop=loop) # 创建连接池
async with pool.acquire() as conn: #从空闲池获取连接的协程。根据需要创建新连接,并且池的大小小于maxsize。
async with conn.cursor() as cur:
await cur.execute("SELECT * from test_biao")
print(cur.description)
r = await cur.fetchall()
print(r)
pool.close() # 连接池关闭
await pool.wait_closed() #等待释放和关闭所有已获取连接的协同程序。应该在close()之后调用,以等待实际的池关闭。
loop = asyncio.get_event_loop()
loop.run_until_complete(test_example(loop))