【问题标题】:Python 3 Update MySQL database tablePython 3 更新 MySQL 数据库表
【发布时间】:2017-08-27 01:18:27
【问题描述】:

我刚刚找到了用于将 Python 连接到 MySQL 数据库的 pymysql 模块。我有一个数据库,其中包含一个名为“loot”的表,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()

【问题讨论】:

    标签: python-3.x mysql-python


    【解决方案1】:

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

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

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

    【讨论】:

    • 我还在学习 :-) 这实际上是元组中的元组?
    • 这是一个方法调用内部的元组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多