【问题标题】:How to pass python's variable output to psql?如何将python变量输出传递给psql?
【发布时间】: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')

标签: python psql


【解决方案1】:

首先,您应该尽可能避免在查询字符串中插入值。它现在被视为糟糕的做法,因为它已被用于 SQL injection 攻击数十年。参数化查询更具抵抗力。

接下来,readline 将终止的新行留在字符串中,这可能不是您想要的。

最后,with 让您无需显式关闭文件。

把它一起煮沸,它给出:

with open('/var/www/html/x', 'r') as read:  # ensure file will be closed
    x_read = read.readline().rstrip()       # clean up the end of the line

mycursor.execute("insert into test (name, code, city, x, y) values (?,?,?,?,?)",
                 ('xxx_wet', '00-000', 'xxx_city', x_read, '19.560'))
mydb.commit()

【讨论】:

  • 感谢您的建议 - 它只是非常糟糕的代码,因为 psql 仍然没有收听......在实施您的答案解决方案之后,仍然没有 X (x_read)。这很恶心,因为我不知道为什么我不能只将字符串/文本变量传递给一条指令。姓名 |代码 |城市 | x | y xxx_wet | 00-00 | | 19.560
  • @Osho 您应该使用调试跟踪(打印)来控制 x_read 实际包含的内容...
  • 我不认为最好的调试器是 print :) x 文件包含两行,例如 1) line first '11.111', 2) sec.行 - '22.222''。 x_read.readline() 仅将其中一个读取为字符串,在此级别可以。我不能只将输出传递给 postgre 指令。非常令人沮丧。如果你们更详细,请告诉我 - 我会编辑帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 2015-04-12
  • 2013-02-27
  • 1970-01-01
  • 2011-11-23
  • 2011-02-17
相关资源
最近更新 更多