python 异步请求 mysql 获取数据的脚本
import asyncio from pprint import pprint import aiomysql.sa as aio_sa async def main(): # 通过异步上下文管理器的方式创建, 会自动帮我们关闭引擎 async with aio_sa.create_engine(host="xx.xxx.xx.xxx", port=3306, user="root", password="root", db="_hanser", connect_timeout=10) as engine: async with engine.acquire() as conn: result = await conn.execute("SELECT * FROM girl") # 此时的 data 是一个列表, 列表里面是 <class 'aiomysql.sa.result.RowProxy'> 对象 data = await result.fetchall() # 将里面的元素转成字典 pprint(list(map(dict, data))) """ [{'age': 16, 'id': 1, 'name': '古明地觉', 'place': '地灵殿'}, {'age': 16, 'id': 2, 'name': '雾雨魔理沙', 'place': '魔法森林'}, {'age': 400, 'id': 3, 'name': '芙兰朵露', 'place': '红魔馆'}] """ loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close()
参考:https://www.cnblogs.com/traditional/p/12290776.html