我刚刚找到了用于将Python连接到MySQL数据库的pymysql模块。我有一个名为“ loot”的表,其中有一个名为“ wins”的列。我的代码包含一个名为“ won”的变量,该变量在SQL行之前被赋予一个值。我希望将变量“ won”输入到id = 1的“ wins”列中。 id = 1行已存在于数据库中。

下面的代码引发错误pymysql.err.InternalError: (1054, "Unknown column 'won' in 'field list'")

我的问题:为什么会出现此错误,我做错了什么?

代码:

import pymysql

# Open database connection
db = pymysql.connect(host='*******',user='******',password='*****',db='******')

# prepare a cursor object using cursor() method
cursor = db.cursor()

won=1

# Prepare SQL query to UPDATE required records
sql = "UPDATE loot SET wins = won WHERE id = 1"

# Execute the SQL command
cursor.execute(sql)

# Commit your changes in the database
db.commit()

# disconnect from server
db.close()

最佳答案

MySQL无法读取变量won,因此必须将其作为参数传递给.execute()

won = 1
sql = "UPDATE loot SET win = %s WHERE id = %s"
cursor.execute(sql,(won,1))
db.commit()


请注意,您必须具有某种容器作为.execute()的第二个参数。在这种情况下,它是一个元组。

08-28 00:04