【问题标题】:How to make asynchronous MySQL operations with modular queries?如何使用模块化查询进行异步 MySQL 操作?
【发布时间】:2020-01-26 17:04:37
【问题描述】:

我目前正在为社区驱动的活动开发一个稍微复杂的不和谐机器人。
目标是提供一个简单的网络界面,部落可以在其中登录并执行他们需要执行的所有操作(例如注册活动、查看统计数据、查看团队等)。
我刚刚完成了根据我的 MySQL 数据库中的表更新用户角色的功能。
由于整个 discord bot 是用异步代码编写的,我想保留我已经建立的架构。
我已经阅读了异步代码,并且知道我必须使用类似 aiomysql 的 Python 模块。
遗憾的是,这些文档对初学者不太友好,这就是我在这里提出问题的原因:

我想做这样的事情:

async def queryDB(query):
  loop = asyncio.get_event_loop()
  def test_example(query):
    conn = yield from aiomysql.connect(host='127.0.0.1', port=3306,
                                       user='root', password='', db='mysql',
                                       loop=loop)

    cur = yield from conn.cursor()
    yield from cur.execute(query)
    print(cur.description)
    results = yield from cur.fetchall()
    yield from cur.close()
    conn.close()
    return results

  var = loop.run_until_complete(test_example(query))
  return var

如您所见,我希望查询是模块化的,并在函数调用中设置参数。我当然希望返回我的结果,以便我以后可以使用它。

此代码一直失败,错误代码为:RuntimeError: This event loop is already running,我不知道如何解决此问题。我如何处理循环以及如何调用我的函数可能存在问题。

有人可以帮忙吗?

【问题讨论】:

    标签: python python-3.x asynchronous mysql-python discord.py


    【解决方案1】:

    当机器人启动并将其附加到机器人时,我会得到一个连接池。下面是一个运行给出的任何查询的示例。

    from discord.ext.commands import Bot, is_owner
    
    bot = Bot('!')
    
    @bot.event
    async def on_ready():
        bot.pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                           user='root', password='', db='mysql',
                                           loop=bot.loop)
    
    @is_owner()  # Only bot owner can run this command
    @bot.command()
    async def query(ctx, *, q):
        async with pool.acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute(q)
                res = await cur.fetchall()
                await ctx.send(str(res))
    
    bot.run("token")
    

    【讨论】:

    • 感谢您的快速回复。查询功能中有一个小错字。你忘记了await cur.execute 中的 C。像魅力一样工作
    猜你喜欢
    • 2019-07-20
    • 2011-10-06
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2016-02-09
    相关资源
    最近更新 更多