记录异步操作mysql 的方法

异步操作mysql

因为比较简单, 只要会使用pymysql 就会使用这个 aiomysql , 直接上代码.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import aiomysql
import asyncio

async def execute(address, user, pwd, database):
# IO 操作, 连接mysql
# coon = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', db='test')
coon = await aiomysql.connect(host=address, port=3306, user=user, password=pwd, db=database)
# io操作, 创建游标
cur = await coon.cursor()
# IO 操作, 执行sql
await cur.execute("show tables;")
# IO 操作, 获取sql 结果
result = await cur.fetchall()
print(result)
# io 操作
await cur.close()
coon.close()
address, user, pwd, database = '127.0.0.1', 'root', '123456', 'test'
# 本地并不存在这个mysql
address1, user1, pwd1, database1 = '127.0.0.2', 'root', '123456', 'test'
task = [
execute(address, user, pwd, database),
# execute(address1, user1, pwd1, database1)
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(task))