如何通过模块化查询进行异步MySQL操作?

问题描述 投票:0回答:1

我目前正在为社区驱动的事件开发一个稍微复杂的Discord机器人。目的是提供一个简单的Web界面,氏族可以在其中登录并完成他们需要做的所有事情(例如注册活动,查看统计信息,查看团队等)。我刚刚完成了将根据我的MySQL数据库中的表更新用户角色的功能。由于整个discord bot是用异步代码编写的,因此我希望保留已建立的架构。我已经读过异步代码,并且知道必须为python使用aiomysql模块之类的东西。遗憾的是,文档对初学者不太友好,这就是为什么我在这里问我的问题:

我想做这样的事情:

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个回答
0
投票

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

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.exeute(q)
            res = await cur.fetchall()
            await ctx.send(str(res))

bot.run("token")
© www.soinside.com 2019 - 2024. All rights reserved.