【协程】13、案例2:异步操作mysql
示例1:
# -*- coding: utf-8 -*-
import aiomysql
import asyncio
async def test_mysql():
# 网络IO操作,连接MySQL
conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='mysql')
# 网络IO操作:创建cursor
cursor = await conn.cursor()
# 网络IO操作:执行mysql
await cursor.execute('select Host, User from user')
# 网络IO操作:获取SQL结果
result = await cursor.fetchall()
print(result)
# 网络IO操作: 关闭连接
await cursor.close()
conn.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(test_mysql())示例2:
# -*- coding: utf-8 -*-
import aiomysql
import asyncio
async def test_mysql(host, password):
print('开始:', host)
# 网络IO操作,连接MySQL
conn = await aiomysql.connect(host=host, port=3306, user='root', password=password, db='mysql')
# 网络IO操作:创建cursor
cursor = await conn.cursor()
# 网络IO操作:执行mysql
await cursor.execute('select Host, User from user')
# 网络IO操作:获取SQL结果
result = await cursor.fetchall()
print(result)
# 网络IO操作: 关闭连接
await cursor.close()
conn.close()
print('结束:', host)
async def main():
tasks = [
asyncio.ensure_future(test_mysql('127.0.0.1', 'root')),
asyncio.ensure_future(test_mysql('47.94.132.145', 'root'))
]
dones, pending = await asyncio.wait(tasks)
for i in dones:
print('i:', i)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())本文来自博客园,作者:郭祺迦,转载请注明原文链接:https://www.cnblogs.com/guojie-guojie/p/16330276.html

浙公网安备 33010602011771号