当前位置:Gxlcms > 数据库问题 > 2.aiomysql实现对数据库异步读取

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

时间:2021-07-01 10:21:17 帮助过:4人阅读

有一个库叫做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)

  技术分享图片

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

 

aiomysql还可以和SQLAlchemy结合

pass

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

标签:pool   sync   oca   user   root   local   bubuko   hone   http   

人气教程排行