【问题标题】:String table name not working in a query with psycopg2字符串表名在使用 psycopg2 的查询中不起作用
【发布时间】: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"

所以,看起来我不能在查询中使用字符串表名。也许还值得注意的是,我连接的是视图,而不是表。谁能建议一种将表名作为变量注入查询的方法?

谢谢。

【问题讨论】:

    标签: python sql psycopg2


    【解决方案1】:

    当你引用一些东西时,它被认为是一个对象,而“d1dbforest.interface.v_monitoring_ind34a4”指的是三个对象,数据库名称,模式名称和视图名称:

    所以你需要单独引用它们:"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

    【讨论】:

    • 查询现在确实有效。可能有点超出最初问题的范围,现在查询返回 None。 print(query.as_string(connection)) 返回 select "country","year","data","use" from "d1dbforest"."interface"."v_monitoring_ind34a4",它在 pgAdmin4 中返回表。所以,我认为查询字符串仍然有问题。以下几行很简单: result = cursor.execute(query) print(result)
    • @Eylül 可能是权限问题或连接到错误的服务器
    • 我下面的代码是错误的。应该是:cursor.execute(query) print(cursor.fetchall()) 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多