Python 使用Psycopg2获取列作为值列表

Python 使用Psycopg2获取列作为值列表,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,尝试使用psycopg2从PostgreSQL数据库提取表和列,并尝试了以下代码: def执行_sql(sql): """ 执行查询并提交 :param sql: :返回: """ 连接信息=获取连接信息() 打印(连接信息) 打印('这是上面的连接信息') 使用psycopg2.connect(**连接信息)作为连接: cur=connection.cursor(cursor\u factory=psycopg2.extras.RealDictCursor) 当前执行(sql) rtn_val

尝试使用psycopg2从PostgreSQL数据库提取表和列,并尝试了以下代码:

def执行_sql(sql):
"""
执行查询并提交
:param sql:
:返回:
"""
连接信息=获取连接信息()
打印(连接信息)
打印('这是上面的连接信息')
使用psycopg2.connect(**连接信息)作为连接:
cur=connection.cursor(cursor\u factory=psycopg2.extras.RealDictCursor)
当前执行(sql)
rtn_val=cur.fetchall()
返回rtn_val
我给出的SQL的输出如下所示:

[RealDictRow([('table_name', 'pg_statistic')]), RealDictRow([('table_name', 'pg_foreign_table')]), RealDictRow([('table_name', 'pg_authid')]), RealDictRow([('table_name', 'pg_shadow')]), RealDictRow([('table_name', 'pg_roles')])]
但只希望输出为:

['pg_statistic','pg_foreign_table', 'pg_authid', 'pg_shadow', 'pg_roles']

你可以这样做:

rtn_val = cur.fetchall()

table_list = [row["table_name"] for row in rtn_val]
```

移除
cursor\u factory=psycopg2.extras.RealDictCursor
请注意,这将是一个元组而不是列表。以下是您拥有的选项:。您需要适应输出内容,因此在这种情况下:[row[0]for row in rtn_val]并且您知道这是什么,这样您也可以使列表理解动态化。用你拥有的,而不是你想要的。