Python 3 更新 MySQL 数据库 table
Python 3 Update MySQL database table
我刚刚找到了用于将 Python 连接到 MySQL 数据库的 pymysql 模块。我有一个数据库设置有一个名为 'loot' 的 table,战利品包含一个名为 '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()
的第二个参数。在本例中它是一个元组。
我刚刚找到了用于将 Python 连接到 MySQL 数据库的 pymysql 模块。我有一个数据库设置有一个名为 'loot' 的 table,战利品包含一个名为 '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()
的第二个参数。在本例中它是一个元组。