如何使用模块化查询进行异步 MySQL 操作?
How to make asynchronous MySQL operations with modular queries?
我目前正在为一个社区驱动的活动开发一个稍微复杂的 discord 机器人。
目标是提供一个简单的网络界面,部落可以在其中登录并做他们需要做的所有事情(比如注册活动、查看统计数据、查看团队等)。
我刚刚完成了根据 MySQL 数据库中的 table 更新用户角色的功能。
由于整个 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
,我不知道如何解决这个问题。我处理循环的方式以及调用函数的方式可能存在问题。
有人可以帮忙吗?
我会在 bot 启动时获得一个连接池并将其附加到 bot。下面是一个运行任何给定查询的示例。
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")
我目前正在为一个社区驱动的活动开发一个稍微复杂的 discord 机器人。
目标是提供一个简单的网络界面,部落可以在其中登录并做他们需要做的所有事情(比如注册活动、查看统计数据、查看团队等)。
我刚刚完成了根据 MySQL 数据库中的 table 更新用户角色的功能。
由于整个 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
,我不知道如何解决这个问题。我处理循环的方式以及调用函数的方式可能存在问题。
有人可以帮忙吗?
我会在 bot 启动时获得一个连接池并将其附加到 bot。下面是一个运行任何给定查询的示例。
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")