Update a PostgreSql table using a Python variable

Question:

I have the following table in my PostgreSql database with 1 row of data.

enter image description here

I want to update the value in the “diagnosis” column (currently 3) to another number. My python code is below:

Based on my code below, the “diagnosis” column should equal whatever number is assigned to the python diagnosis variable. In this case, the “diagnosis” column in my table should equal 5.

diagnosis = 5; 

# eyeball

conn = psycopg2.connect("dbname=eyeballdbfinal user=postgres")
print ("Database opened successfully")

cur = conn.cursor()
cur.execute("UPDATE eyeballtables set DIAGNOSIS = diagnosis where id = 1") # fix this
conn.commit()
print("Total updated rows:", cur.rowcount)

But my SQL code inside my python is not working. Specifically, after running my python code above, my table should have 5 as the diagnosis. Instead, nothing changes. I think this part of the code DIAGNOSIS = diagnosis is not working.

What am I doing wrong?

Asked By: PineNuts0

||

Answers:

Use the variable as a parameter:

cur.execute("UPDATE eyeballtables set DIAGNOSIS = %s where id = 1", (diagnosis,))

Read: Passing parameters to SQL queries

Answered By: klin