python - 如何在 aiomysql 中使用连接池

标签 python python-3.x python-asyncio

我只是不知道如何通过阅读 aiohttp examples 或谷歌来重用 aiomysql 连接池。 这是我的代码

import aiomysql
import asyncio


async def select(loop, sql):
    pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                      user='root', password='123456',
                                      db='test', loop=loop)
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            r = await cur.fetchone()
            print(r)


async def insert(loop, sql):
    pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                      user='root', password='123456',
                                      db='test', loop=loop)
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            await conn.commit()


async def main(loop):
    c1 = select(loop=loop, sql='select * from minifw')
    c2 = insert(loop=loop, sql="insert into minifw (name) values ('hello')")
    tasks = [
        asyncio.ensure_future(c1),
        asyncio.ensure_future(c2)
    ]
    return await asyncio.gather(*tasks)

if __name__ == '__main__':
    cur_loop = asyncio.get_event_loop()
    cur_loop.run_until_complete(main(cur_loop))

如果我运行这段代码,create_pool 将被执行两次。所以我想知道如何更改这段代码以重用 aiomysql 连接池。

谢谢!

最佳答案

你可以在main func中定义pool,像这样:

import aiomysql
import asyncio


async def select(loop, sql, pool):
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            r = await cur.fetchone()
            print(r)


async def insert(loop, sql, pool):
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            await conn.commit()


async def main(loop):
    pool = await aiomysql.create_pool(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='123456',
        db='test',
        loop=loop)
    c1 = select(loop=loop, sql='select * from minifw limit 1', pool=pool)
    c2 = insert(loop=loop, sql="insert into minifw (name) values ('hello')", pool=pool)

    tasks = [asyncio.ensure_future(c1), asyncio.ensure_future(c2)]
    return await asyncio.gather(*tasks)


if __name__ == '__main__':
    cur_loop = asyncio.get_event_loop()
    cur_loop.run_until_complete(main(cur_loop))

关于python - 如何在 aiomysql 中使用连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44481826/

相关文章:

python - 在 Django 模板中包含 url 变量

python-3.x - Chrome 驱动程序错误 selenium 消息 : session not created from disconnected: unable to connect to renderer

Python 请求流异步

python - 使用 Azure 表客户端库从多个不同的 Azure 表异步检索数据

python - 更改 Geckodriver for Python Selenium 的日志级别

Python 正则表达式搜索与贪婪运算符

python - 只能将 str (不是 "bytes")连接到 str

python asyncio - ctrl+c 上的清理事件循环?和 close() 与 stop()

尝试下载文件时,Python 请求抛出 Connection Broken : ChunkedEncodingError with http. client.IncompleteRead

python-3.x - 导入 'PunktWordTokenizer' 时出错