我使用此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
双引号导致查询失败。如何使它们消失?
我将查询更改为如下格式,现在效果更好:
query = sql.SQL('SELECT * FROM {}.{} LIMIT 0').format(sql.Identifier(schema), sql.Identifier(table))
谢谢!