zoukankan      html  css  js  c++  java
  • aiomysql 如何使用

    需要注意的是 aiomysql 是基于协程的,因此需要通过 await 的方式来调用。
    使用 aiomysql 连接到数据库可以使用 aiomysql.connect() 方法。它会返回一个 connection 对象, connection 对象代表了一个数据库连接:
    import aiomysql
    async def run(loop):
        conn = await aiomysql.connect(
            host='127.0.0.1', 
            port=3306, 
            user='root', 
            password='password', 
            db='test', 
            loop=loop)
    
        # 执行数据库操作 ...
    
        conn.close()
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run(loop))
    连接成功后,可以通过 connect 对象得到一个 cursor 对象,你可以通过 cursor 对象来调用数据库指令,从而完成增删改查等操作
       cursor = await conn.cursor()
        await cursor.execute("INSERT INTO user set email='hahaha123@outlook.com', phonenumber='12345678910'")
        print(cursor.rowcount)
    
        # 必须调用 commit, 操作才会真正在数据库中执行。
        await conn.commit()
        conn.close()
    aiomysql.connect() 的参数中有一个 autocommit 参数,默认为 False, 你可以把它设置为 True, 这样就不需要手动调用 connection.commit() 了。

    连接池

    除了使用之前介绍过的 aiomysql.connect() 方法来连接到数据库,aiomysql 还提供了连接池的接口,有了连接池的话,不必频繁打开和关闭数据库连接。
    import aiomysql
    import asyncio
    
    g_pool = None
    
    async def fetch_user():
        global g_pool
        # 从连接池中获取连接
        with (await g_pool) as conn:
            # 用这个连接执行数据库操作
            cursor = await conn.cursor()
            await cursor.execute("SELECT * FROM user")
            rows = await cursor.fetchall()
            print(rows)
            # with 退出后,将自动释放 conn 到 g_pool 中
    
    async def fetch_blog():
        global g_pool
        with (await g_pool) as conn:
            cursor = await conn.cursor()
            await cursor.execute("SELECT * FROM blog")
            rows = await cursor.fetchall()
            print(rows)
    
    async def run(loop):
        global g_pool
        g_pool = await aiomysql.create_pool(
            host='127.0.0.1', 
            port=3306, 
            user='root', 
            password='password', 
            db='test', 
            autocommit=True,
            minsize=1,
            maxsize=10, 
            loop=loop)
    
        await fetch_user()
        await fetch_blog()
    
        g_pool.close()
        await g_pool.wait_closed()
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run(loop))
    进入 fetch_user() 或 fetch_blog() 协程后,首先要做的是通过 with (await g_pool) as conn 来从连接池中取出一个连接,因为池中的可能已经被用完,
    这时候需要等待,所以这里需要通过 await g_pool 的方式来调用。
  • 相关阅读:
    后端返回文件前端实现下载功能
    Oracle 树操作(select…start with…connect by…prior)
    javascript异步加载的三种解决方案
    百度地图 异步加载
    jQuery中的siblings
    Jquery点击表格单位时选中其中的Radio的三个方法
    Oracle自增长ID
    Oracle修改时间报:ORA-01830: 日期格式图片在转换整个输入字符串之前结束的解决办法
    Oracle sqlldr导入导出txt数据文件详解
    SQL Server 2012大数据导入Oracle的解决方案
  • 原文地址:https://www.cnblogs.com/topass123/p/13403926.html
Copyright © 2011-2022 走看看