【发布时间】:2021-05-10 13:07:10
【问题描述】:
我想使用列名和表名的变量生成动态查询。这是我的代码:
query = sql.SQL("select {fields} from {table}").format(fields=sql.SQL(',').join([
sql.Identifier(country_column_id),
sql.Identifier(time_column_id),
sql.Identifier(value_column_id),
sql.Identifier(type_column_id),
]),
table=sql.Identifier(table_name))
cursor.execute(query)
我收到以下错误:
psycopg2.errors.UndefinedTable:关系“d1dbforest.interface.v_monitoring_ind34a4”不存在 第 1 行:从“d1dbforest.interf...”中选择“国家”、“年份”、“数据”、“使用”...
我注意到在 pgAdmin4 中我可以运行
select "country","year","data","use" from d1dbforest.interface.v_monitoring_ind34a4
但不是
select "country","year","data","use" from "d1dbforest.interface.v_monitoring_ind34a4"
所以,看起来我不能在查询中使用字符串表名。也许还值得注意的是,我连接的是视图,而不是表。谁能建议一种将表名作为变量注入查询的方法?
谢谢。
【问题讨论】: