【问题标题】:removing quotes when interpolating query value in psycopg2在 psycopg2 中插入查询值时删除引号
【发布时间】:2017-11-09 16:32:50
【问题描述】:

已连接到 this question,但我缺少一些东西。

当我运行以下内容时

table_name = 'my_schema.my_table'
cur.execute(sql.SQL('SELECT col1, col2 FROM {}').format(sql.Identifier(table_name)))

发送到数据库的查询是

SELECT col1, col2 FROM "myschema.myname"

我得到了错误:

"relation "myschema.myname" does not exist"

我希望查询是

SELECT col1, col2 FROM myschema.myname

当我将它直接传递给 cur.execute 时,我没有问题。


如果有帮助,我会使用 .ini 文件连接到 this tutorial 之后的数据库,在我的情况下,该文件如下所示:

[postgresql]
host=ip_no_of_host
database=name_of_db
user=username
password=password

【问题讨论】:

  • 感谢您的建议。我不只连接到数据库的特定架构,如果我将它直接传递给 cur.executemyschema.mytable 也可以正常工作。
  • 我已经用 conn 详细信息更新了我的问题。删除模式限定符不起作用 - 我仍然在表名周围加上引号。我认为这不是问题,因为问题是删除引号。正如我所说的cur.execute('SELECT col1, col2 FROM myschema.myname') 工作正常。

标签: python sql postgresql psycopg2


【解决方案1】:
schema_name = 'my_schema'
table_name = 'my_table'
cur.execute(sql.SQL('SELECT col1, col2 FROM {}.{}').format(
    sql.Identifier(schema_name), sql.Identifier(table_name)
    )
)

或者只是

table_name = 'my_table'
cur.execute(sql.SQL('SELECT col1, col2 FROM my_schema.{}').format(
    sql.Identifier(table_name)
    )
)

【讨论】:

  • 谢谢,解决了。这是因为 sql.Identifier(_str_) 对象映射到原子 postgres 对象吗?
猜你喜欢
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 2017-01-28
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多