码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2018-12-23 22:08:15      阅读:345      评论:0      收藏:0      [点我收藏+]

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

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

原文地址:https://www.cnblogs.com/traditional/p/10165429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!