如何在 MySQL 中将 Python 变量与 UPDATE 命令一起使用?

How can I use Python Variables with the UPDATE command in MySQL?

我一直在尝试将这部分作为我的 A-Level 项目的一部分,我在 MyPHPAdmin 中有一个数据库,我的代码获取一个值,将其与预设值进行比较,如果没有变化,则使用数据库来存储新值。 (由于我的代码的其他部分,我不能只插入新数据)。我一直在尝试使用一个变量,该变量的值从输入框中存储在其中,但是它拒绝获取该值。我已经尝试了很多东西,但我似乎无法让它工作,而且每次我尝试不同的东西时,我似乎都会遇到不同的错误。我担心这可能只是我想念的一些简单的东西,但对于我的生活我无法弄清楚它让我发疯。 (是的,我已经查看了文档,但它对我的情况没有多大用处)

我的代码:

mycursor = database.cursor(buffered=True)
mycursor.execute("SELECT name FROM creationPokemon")
myresult = mycursor.fetchone()[0]
print(myresult)

if myresult == "Placeholder1":
    sql = ("UPDATE creationPokemon SET name = %s WHERE name = %s")
    val = ('Placeholder1', cName)
else:
    myresult = mycursor.fetchone()[0]
    print(myresult)

mycursor.execute(sql)
database.commit()

我这次登陆的错误是:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s WHERE name = %s' at line 1

非常感谢任何帮助。

python 和 mysql 连接器在使用元组时至少需要 2 个 dimemsns,并且需要填充两个占位符

mycursor = database.cursor(buffered=True)
mycursor.execute("SELECT name FROM creationPokemon")
myresult = mycursor.fetchone()[0]
print(myresult)

if myresult == "Placeholder1":
    sql = "UPDATE creationPokemon SET name = %s WHERE name = %s"
    val = (cName,cName)

    mycursor.execute(sql,val)
    database.commit()
else:
    myresult = mycursor.fetchone()[0]
    print(myresult)