python 非同步請求 mysql 獲取資料的指令碼
阿新 • • 發佈:2022-05-10
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()