如何从psycopg2游标获取列名列表?

2024-05-04 19:11:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一种直接从所选列名生成列标签的通用方法,回想一下python的psycopg2模块支持此功能


Tags: 模块方法功能标签psycopg2
3条回答

来自Mark Lutz的“编程Python”:

curs.execute("Select * FROM people LIMIT 0")
colnames = [desc[0] for desc in curs.description]

要在单独的查询中获取列名,可以查询information\u schema.columns表

#!/usr/bin/env python3

import psycopg2

if __name__ == '__main__':
  DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'

  column_names = []

  with psycopg2.connect(DSN) as connection:
      with connection.cursor() as cursor:
          cursor.execute("select column_name from information_schema.columns where table_schema = 'YOUR_SCHEMA_NAME' and table_name='YOUR_TABLE_NAME'")
          column_names = [row[0] for row in cursor]

  print("Column names: {}\n".format(column_names))

要在与数据行相同的查询中获取列名,可以使用光标的描述字段:

#!/usr/bin/env python3

import psycopg2

if __name__ == '__main__':
  DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'

  column_names = []
  data_rows = []

  with psycopg2.connect(DSN) as connection:
    with connection.cursor() as cursor:
      cursor.execute("select field1, field2, fieldn from table1")
      column_names = [desc[0] for desc in cursor.description]
      for row in cursor:
        data_rows.append(row)

  print("Column names: {}\n".format(column_names))

您可以做的另一件事是创建一个游标,您可以使用该游标按列的名称引用列(这是一种需要,让我首先进入本页):

import psycopg2
from psycopg2.extras import RealDictCursor

ps_conn = psycopg2.connect(...)
ps_cursor = psql_conn.cursor(cursor_factory=RealDictCursor)

ps_cursor.execute('select 1 as col_a, 2 as col_b')
my_record = ps_cursor.fetchone()
print (my_record['col_a'],my_record['col_b'])

>> 1, 2

相关问题 更多 >