I have just found the pymysql module for connecting Python to a MySQL database. I have a database set up with a table named 'loot', loot contains a column called 'wins'. My code contains a variable named 'won' that is given a value right before the SQL line. I want the variable 'won' to be entered into the 'wins' column where id=1. The id=1 row already exists in the database.
The code below throws an error pymysql.err.InternalError: (1054, "Unknown column 'won' in 'field list'")
My Question: Why am I getting this error and what am I doing incorrectly?
The 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()
Execute the UPDATE query, using cursor.execute() Execute the UPDATE query using cursor. execute() method. This method execute the operation stored in the UPDATE query.
MySQL isn't able to read the variable won
so you must pass it in as an argument to .execute()
:
won = 1
sql = "UPDATE loot SET win = %s WHERE id = %s"
cursor.execute(sql,(won,1))
db.commit()
Please note that you have to have a container of some sort as the second argument to .execute()
. In this case it is a tuple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With