【协程】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 @   郭祺迦  阅读(134)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示