【发布时间】:2021-02-17 13:01:35
【问题描述】:
我们有 'var/www/html/x' 文件,它有两行。 x_read 变量允许我们只读取第一行。 例如 - 当我们想使用这个 x_read 保存这一行时,没有问题。
当我们想在 postgresql 指令中使用 x_read 时出现问题。没有像 INTERNAL SERVER ERR 之类的错误,应用程序继续运行,但是 x_read 的值 没有保存在数据库中。
我们也尝试过使用 mysql,但仍然存在随机“崩溃”,我的意思是 - 有时有效,有时无效。
如何将数据从 python 变量插入到 postgres 指令/表/选择/等?
代码如下:
read = open('/var/www/html/x', 'r')
x_read = read.readline()
mycursor.execute("insert into test (name, code, city, x, y) values ('xxx_wet', '00-000', 'xxx_city'," +"'"+ x_read +"'"+ ", '19.560');")
mydb.commit()
【问题讨论】:
-
为什么不直接使用
f-strings作为:f"insert into test (name, code, city, x, y) values ('xxx_wet', '00-000', 'xxx_city', '{x_read}' '19.560')" -
你好,你可以这样试试:
mycursor.execute("insert into test (name, code, city, x, y) values (%s, %s, %s, %s, %s);", ('xxx'wet', '00-000', 'xxx_city', x_read, '19.560')) -
我们也在使用 f' 字符串 - 没关系 - 好像 psql 没有看到 python var。
-
您可以尝试@T0ny1234 的建议或使用
format()以及:"insert into test (name, code, city, x, y) values ( {}, {}, {}, {}, {} );".format('xxx_wet', '00-000', 'xxx_city', x_read, '19.560')