【问题标题】:How do i make it to check if there is a same tags name already exist?我如何检查是否已经存在相同的标签名称?
【发布时间】:2020-11-27 22:29:24
【问题描述】:

我创建了一个自定义命令,更像是自定义标签命令,但我想检查一下,如果有相同的标签名称,发送一条消息,表明该名称的标签已经存在 我尝试使用此代码,但它不断将新标签记录到 sqlite 虽然它已经存在。

    @tags.command()
    async def create(self, ctx, tag=None, *,text=None):
        db = sqlite3.connect('main.db')
        cursor = db.cursor()
        cursor.execute(f"SELECT text FROM tags WHERE guild_id = {ctx.guild.id} and tag")
        result = cursor.fetchone()
        if result is None:
            sql = (f"INSERT INTO tags(guild_id, tag, text) VALUES(?,?,?)")
            val = (ctx.guild.id, tag, text)
            await ctx.send(f'Created {tag}!')
            cursor.execute(sql, val)
            db.commit()
        if result is not None:
            await ctx.send(f'Tag named {tag} was already exist.')
        cursor.close()
        db.close()

【问题讨论】:

    标签: sqlite discord discord.py discord.py-rewrite


    【解决方案1】:

    查询的WHERE 子句必须包含tag 列的条件:

    cursor.execute(f"SELECT text FROM tags WHERE guild_id = {ctx.guild.id} and tag = {tag}")
    

    也许没有必要检查guild_id:

    cursor.execute(f"SELECT text FROM tags WHERE tag = {tag}")
    

    或者使用?占位符:

    cursor.execute("SELECT text FROM tags WHERE tag = ?", (tag,))
    

    【讨论】:

    • 又是你?,无论如何第一个选项有效,我还需要检查 guild_id 因为每个公会都使用了标签
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2015-06-17
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多