【问题标题】:discord.py Sqlite3 remove () from selectdiscord.py Sqlite3 remove() from select
【发布时间】:2020-12-10 10:05:02
【问题描述】:

很抱歉这个奇怪的问题,但我不知道如何措辞。但我正在为我的机器人制作一个经济系统。我想做一个命令>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 文档,我很乐意阅读它们

【问题讨论】:

    标签: python python-3.x sqlite discord.py


    【解决方案1】:

    因此,与您的问题无关,但请避免使用 f 字符串进行 SQL 查询。使用 f-strings(或等效项)是导致安全问题的常见原因,因此最好避免养成这种习惯。相反,请始终使用占位符并将值作为单独的参数传递:

    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.guild.id, ctx.author.id))
    row = cursor.fetchone()
    if row is None:
        ... handle the situation ...
    wallet, bank = row
    

    【讨论】:

      猜你喜欢
      • 2022-12-27
      • 2022-12-16
      • 2021-09-24
      • 2022-12-28
      • 2014-02-14
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 2012-03-16
      相关资源
      最近更新 更多