【协程】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())
posted @ 2022-05-31 14:12  郭祺迦  阅读(145)  评论(0)    收藏  举报