Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 Update MySQL database table

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()
like image 210
Brandon Avatar asked Apr 01 '17 23:04

Brandon


People also ask

How do I run a Python UPDATE query?

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.


Video Answer


1 Answers

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.

like image 166
mechanical_meat Avatar answered Sep 23 '22 22:09

mechanical_meat