psycopg2表名作为参数失败,并用双引号引起来

问题描述 投票:0回答:1

我使用此python函数从postGres中的不同表获取列名。

def get_table_columns(conn, table):
"""
Retrieve a list of column names in a table
:param conn:
:param table:
:return: List of column names
"""
try:
    query = sql.SQL('SELECT * FROM {} LIMIT 0').format(sql.Identifier(table))
    print(query.as_string(conn))
    with conn as c:
        with c.cursor() as cur:
            cur.execute(query)
            return [desc[0] for desc in cur.description]

except psycopg2.DatabaseError as de:
    logger.error("DatabaseError in get_table_columns: {0}".format(str(de)))
    raise de
except Exception as ex:
    logger.error("Exception in get_table_columns: {0}".format(str(ex)))
    raise ex

我收到错误,“ v43fs.evt_event_cycle关系”不存在。

打印语句如下所示:SELECT * FROM“ v43fs.evt_event_cycle” LIMIT 0

双引号导致查询失败。如何使它们消失?

parameters psycopg2
1个回答
0
投票

我将查询更改为如下格式,现在效果更好:

query = sql.SQL('SELECT * FROM {}.{} LIMIT 0').format(sql.Identifier(schema), sql.Identifier(table))

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.