【问题标题】:discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IntegrityError: UNIQUE constraint failed: main.Playersdiscord.ext.commands.errors.CommandInvokeError:命令引发异常:IntegrityError:唯一约束失败:main.Players
【发布时间】:2023-03-17 21:45:01
【问题描述】:

如果提到某人,我正在尝试让机器人将用户 id 添加到数据库中,当提到某人时,它会将存储在数据库中的 id 值与提到的 id 进行比较,如果它不在数据库中,它会添加它但是我不断收到标题中的错误。我知道这意味着什么,它试图将提到的 id 插入数据库,但它是唯一的并且已经存在,因此它显示给定的错误,这使它成为一个逻辑问题

    @commands.command()
    async def add(self, ctx, user:discord.User):
        global sql 
        global val
        if ctx.message.author.guild_permissions.manage_messages:
            db = sqlite3.connect('main.sqlite')
            cursor = db.cursor()
            cursor.execute(f"SELECT Players FROM main")
            result = cursor.fetchall()
            if user.id in result:
                await ctx.send(f"<@{user.id}> is already in teh database")
            else:
                sql = ("INSERT INTO main(Players) VALUES(?)")
                val = (user.id,)
                await ctx.send(f"<@!{user.id}> has been added")
            cursor.execute(sql,val)
            db.commit()
            cursor.close()
            db.close()

【问题讨论】:

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


    【解决方案1】:

    原来有一种方法更清洁,效果更好

    
    
        @commands.command()
        async def add(self, ctx, user:discord.User):
            if ctx.message.author.guild_permissions.manage_messages:
                db = sqlite3.connect('main.sqlite')
                cursor = db.cursor()
                try:
                    cursor.execute(f"INSERT INTO main(Players) VALUES({user.id})")
                    await ctx.send(f"<@!{user.id}> has been added")
                except sqlite3.IntegrityError:
                    await ctx.send(f"<@{user.id}> is already in teh database")
                db.commit()
                cursor.close()
                db.close()
    

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2016-07-30
      相关资源
      最近更新 更多