gpt4 book ai didi

python - 使用 Python 变量更新 PostgreSql 表

转载 作者:行者123 更新时间:2023-11-29 13:08:27 26 4
gpt4 key购买 nike

我的 PostgreSql 数据库中有下表,其中包含 1 行数据。

enter image description here

我想将“诊断”列中的值(当前为 3)更新为另一个数字。我的 python 代码如下:

根据我下面的代码,“诊断”列应该等于分配给 python 诊断变量的任何数字。在这种情况下,我表中的“诊断”列应等于 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 代码之后,我的表应该有 5 作为诊断。相反,什么都没有改变。我认为这部分代码 DIAGNOSIS = diagnosis 不起作用。

我做错了什么?

最佳答案

使用变量作为参数:

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

阅读:Passing parameters to SQL queries

关于python - 使用 Python 变量更新 PostgreSql 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58141337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com