1. 程式人生 > 其它 >【協程】13、案例2:非同步操作mysql

【協程】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())