字符串 table 名称在使用 psycopg2 的查询中不起作用
String table name not working in a query with psycopg2
我想使用列名和 table 名称的变量生成动态查询。这是我的代码:
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: relation "d1dbforest.interface.v_monitoring_ind34a4" does not exist
LINE 1: select "country","year","data","use" from "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"
所以,看起来我不能在查询中使用字符串 table 名称。也许还值得注意的是,我正在连接到一个视图,而不是 table。谁能建议一种将 table 名称作为变量注入查询的方法?
谢谢。
当你引用某物时,它被视为一个对象,而“d1dbforest.interface.v_monitoring_ind34a4”指的是 3 个对象,数据库名称,模式名称和视图名称:
所以需要分别引用:"d1dbforest"."interface"."v_monitoring_ind34a4"
所以:
select "country","year","data","use" from "d1dbforest"."interface"."v_monitoring_ind34a4"
那么你必须在标识符中指定它:
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(db_name,schema_name,table_name))
参考:https://www.psycopg.org/docs/sql.html#module-psycopg2.sql
我想使用列名和 table 名称的变量生成动态查询。这是我的代码:
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: relation "d1dbforest.interface.v_monitoring_ind34a4" does not exist LINE 1: select "country","year","data","use" from "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"
所以,看起来我不能在查询中使用字符串 table 名称。也许还值得注意的是,我正在连接到一个视图,而不是 table。谁能建议一种将 table 名称作为变量注入查询的方法?
谢谢。
当你引用某物时,它被视为一个对象,而“d1dbforest.interface.v_monitoring_ind34a4”指的是 3 个对象,数据库名称,模式名称和视图名称:
所以需要分别引用:"d1dbforest"."interface"."v_monitoring_ind34a4"
所以:
select "country","year","data","use" from "d1dbforest"."interface"."v_monitoring_ind34a4"
那么你必须在标识符中指定它:
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(db_name,schema_name,table_name))
参考:https://www.psycopg.org/docs/sql.html#module-psycopg2.sql