Python 3 Update MySQL database table

I just found the pymysql module to connect Python to MySQL database. I have a database set up with a table named "loot", the column contains a "wins" column. My code contains a variable named "won" that gets the value right before the SQL string. I want the variable "won" to be entered in the "wins" column where id = 1. Id = 1 row already exists in the database.

Below is the error code pymysql.err.InternalError: (1054, "Unknown column 'won' in 'field list'")

My question is: Why am I getting this error and what am I doing wrong?

Code:

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()

      

+3


source to share


1 answer


MySQL cannot read the variable won

, so you must pass it as an argument .execute()

:

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

      



Note that .execute()

you must have a container of some type as the second argument for . In this case, it is a tuple.

+2


source







All Articles