如何解决discord.py Sqlite3从选择
很抱歉这个奇怪的问题,但我不知道该如何措辞。但是我正在为我的机器人制作一个经济系统。我要创建一个命令>balance
,该命令将显示用户的钱包和银行。由于用户可以通过漫游器在多个服务器中使用,因此从他们的guild_id和user_id中获取。
@client.command()
async def balance(ctx):
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT user_id FROM economy WHERE guild_id = {ctx.guild.id}")
result = cursor.fetchone()
if result is None:
await ctx.send("Umm it seems that you do not have an account. You can open an account by typing `>open_account`.")
elif result is not None:
cursor.execute(f"SELECT wallet FROM economy WHERE guild_id = {ctx.guild.id} AND user_id = {ctx.author.id}")
wallet = cursor.fetchone()
cursor.execute(f"SELECT bank FROM economy WHERE guild_id = {ctx.guild.id} AND user_id = {ctx.author.id}")
bank = cursor.fetchone()
embed=discord.Embed(title="Welcome to the Bank of Furry!!",description="{}'s balance:".format(ctx.author.name),color=0xe20303)
embed.add_field(name="Wallet Balance: ",value=wallet,inline=True)
embed.add_field(name="Bank Balance: ",value=bank,inline=True)
await ctx.send(embed=embed)
db.close()
cursor.close()
当打印出嵌入时,其钱包为('0',),银行为('0',)。我想知道如何摆脱('',)。
注意我正在编写我的机器人代码时正在学习sqlite3。因此,如果您对此有任何好的sqlite3文档,我希望阅读它们
解决方法
因此,与您的问题无关,但请避免对SQL查询使用f字符串。使用f字符串(或等效字符串)是造成安全问题的常见原因,因此最好避免养成这种习惯。相反,请始终使用占位符并将值作为单独的参数传递进来:
cursor.execute("SELECT wallet FROM economy WHERE guild_id = ? AND user_id = ?",(ctx.guild.id,ctx.author.id))
对于问题本身,fetchone()
返回您选择的所有列的元组,即使只有一个;要打开它的包装,可以使用类似以下内容的
wallet,= cursor.fetchone()
请注意,.fetchone()
可能在没有结果时返回None
,因此您可能需要将其分成两个语句:
row = cursor.fetchone()
if row is None:
... handle the situation ...
wallet,= row
如果您想要的不止一列(如此处所示),则可以使用相同的SELECT语句检索它们,因此下一个版本的代码为:
cursor.execute("SELECT wallet,bank FROM economy WHERE guild_id = ? AND user_id = ?",ctx.author.id))
row = cursor.fetchone()
if row is None:
... handle the situation ...
wallet,bank = row
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。