使用 Python 变量更新 PostgreSql table
Update a PostgreSql table using a Python variable
我的 PostgreSql 数据库中有以下 table,其中有 1 行数据。
我想将 "diagnosis" 列中的值(当前为 3)更新为另一个数字。我的 python 代码如下:
根据我下面的代码,"diagnosis" 列应该等于分配给 python 诊断变量的任何数字。在这种情况下,我的 table 中的 "diagnosis" 列应该等于 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)
但是 python 中的 SQL 代码无法正常工作。具体来说,在上面 运行 我的 python 代码之后,我的 table 应该有 5 作为诊断。相反,什么都没有改变。我认为这部分代码 DIAGNOSIS = diagnosis 不起作用。
我做错了什么?
使用变量作为参数:
cur.execute("UPDATE eyeballtables set DIAGNOSIS = %s where id = 1", (diagnosis,))
我的 PostgreSql 数据库中有以下 table,其中有 1 行数据。
我想将 "diagnosis" 列中的值(当前为 3)更新为另一个数字。我的 python 代码如下:
根据我下面的代码,"diagnosis" 列应该等于分配给 python 诊断变量的任何数字。在这种情况下,我的 table 中的 "diagnosis" 列应该等于 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)
但是 python 中的 SQL 代码无法正常工作。具体来说,在上面 运行 我的 python 代码之后,我的 table 应该有 5 作为诊断。相反,什么都没有改变。我认为这部分代码 DIAGNOSIS = diagnosis 不起作用。
我做错了什么?
使用变量作为参数:
cur.execute("UPDATE eyeballtables set DIAGNOSIS = %s where id = 1", (diagnosis,))