我想要一种从选定的列名直接生成列标签的通用方法,并且记得python的psycopg2模块支持这一特性。


当前回答

摘自Mark Lutz的《Programming Python》:

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

其他回答

摘自Mark Lutz的《Programming Python》:

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

要在单独的查询中获得列名,可以查询information_schema。表列。

#!/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))

要在相同的查询中获取列名作为数据行,您可以使用游标的description字段:

#!/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))
 # You can use this function
 def getColumns(cursorDescription):
     columnList = []
     for tupla in cursorDescription:
         columnList.append(tupla[0])
     return columnList 

我注意到你必须在查询后使用cursor.fetchone()来获取cursor.description中的列列表(即在[desc[0] for desc in curs.description])

我也曾经面临过类似的问题。我用一个简单的技巧来解决这个问题。 假设您在一个列表中有这样的列名

col_name = ['a', 'b', 'c']

然后你就可以跟着做了

for row in cursor.fetchone():
    print zip(col_name, row)