简体   繁体   English

使用 Psycopg2 获取列作为值列表

[英]Fetch column as a list of values with Psycopg2

Trying to use psycopg2 for extracting tables and columns from PostgreSQL database and tried the below code:尝试使用 psycopg2 从 PostgreSQL 数据库中提取表和列并尝试以下代码:

def execute_sql(sql):
    """
        Execute a query and commits
        :param sql:
        :return:
        """
    conn_info = get_connection_info()
    print(conn_info)
    print('this is conn info above')
    with psycopg2.connect(**conn_info) as connection:
        cur = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cur.execute(sql)
        rtn_val = cur.fetchall()
    return rtn_val

The output for the SQL which I'm giving coming out as:我给出的 SQL 的 output 如下:

[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')])]

But just want the output as:但只希望 output 为:

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

You could do something like:您可以执行以下操作:

rtn_val = cur.fetchall()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM