【问题标题】:Discord.py Insert Values into Database using mysql-connectorDiscord.py 使用 mysql-connector 将值插入数据库
【发布时间】:2020-03-29 18:59:47
【问题描述】:

我正在尝试通过用户输入将值插入数据库。以下代码无需用户输入即可工作:

mycursor = mydb.cursor()
sql = "INSERT INTO DiscordData (UserID, Code) VALUES (%s, %s)"
val = ("1234", "foobar")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

但是,当我将代码传递到命令处理程序以供用户输入时,并没有插入数据:

@bot.command()
async def foo(message, arg):
    if isinstance(message.channel, discord.DMChannel):
        await message.send(arg)
        mycursor = mydb.cursor()
        sql = "INSERT INTO DiscordData (UserID, Code) VALUES (%s, %s)"
        val = ("123", arg)
        await mycursor.execute(sql, val)
        await mydb.commit()
        print(mycursor.rowcount, "record inserted.")

【问题讨论】:

  • 您使用的是什么数据库库?如果它不是显式异步的,那么await mycursor.execute 没有意义,会导致错误。

标签: python sql discord.py mysql-connector


【解决方案1】:

我在一些项目中使用过 mysql 和 discord bot,因此我可以在这里为您提供一些见解。

首先,您不需要在 mycursor.executemydb.commit() 调用中使用 await。

其次,我编写代码的方式有点不同,尽管这样做是值得的,但我知道它应该可以工作。我有一个 SQLCmds.py 文件,它被导入到主要的 discord bot python 文件中。 SQLCmds.py 中包含将新信息放入 MySQL 数据库的所有必要函数。因此,您不是在 discord 机器人的代码中调用 SQL 函数,而是调用类似于您的顶级代码的函数并传递机器人拥有的任何信息。

例如,这里有一个禁用词检查:

def checkBannedWord(banned_word):
    mycursor.execute("SELECT filtered_to FROM banned_word_table WHERE banned_word = '"+str(banned_word).lower()+"'")
    result = mycursor.fetchall()
    if result != []:
        return result[0][0]
    else:
        return False

在您的 discord 机器人代码中,您可以checkBannedWord(banned_word) 并调用此 SQL 函数。这将使整个过程对您来说更加简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 2014-07-21
    • 2015-06-30
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多