有一个库叫做aiomysql,这是一个基于asyncio和pymysql的库。至于为什么可以在tornado中使用,是因为高版本tornado的底层使用了asyncio。

import asyncio
import aiomysql

async def test(loop):
    # 这里的loop就是我们通过asyncio.get_event_loop()创建的,但是其实可以不传,因为会自动创建一个
    async with aiomysql.create_pool(host="localhost", port=3306, user="root",
                                    password="zgghyys123", db="satori", loop=loop) as pool:
        async with pool.acquire() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute("select * from girl")
                data1 = await cursor.fetchone()
                data2 = await cursor.fetchall()
                print(data1)
                print(data2)

        pool.close()
        await pool.wait_closed()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(test(loop))
(0, '古明地觉', 16, 'f')
((1, '椎名真白', 17, 'f'), (2, '古河渚', 20, 'f'))

  我们看看可不可以使用tornado去启动aiomysql

import tornado.ioloop
import aiomysql

async def test():
    # 这里的loop就是我们通过asyncio.get_event_loop()创建的,但是其实可以不传,因为会自动创建一个
    async with aiomysql.create_pool(host="localhost", port=3306, user="root",
                                    password="zgghyys123", db="satori") as pool:
        async with pool.acquire() as conn:
            async with conn.cursor() as cursor:
                await cursor.execute("select * from girl")
                data1 = await cursor.fetchone()
                data2 = await cursor.fetchall()
                print(data1)
                print(data2)

        pool.close()
        await pool.wait_closed()

if __name__ == '__main__':
    tornado.ioloop.IOLoop.current().run_sync(test)

  2.aiomysql实现对数据库异步读取-LMLPHP

一样是可以的,因为tornado的底层事件循环使用的便是asyncio

aiomysql还可以和SQLAlchemy结合

pass

05-12 01:23