2012-04-20 4 views

답변

116

:

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

열 이름 만 원할 경우 테이블의 모든 행을 선택하지 마십시오. 이것은보다 효율적이다 :'curs.execute ("SELECT * FROM people LIMIT 0")' – Demitri

+1

뷰의 컬럼 이름을 얻는 것이 쉽지만 'information_schema'. – wjv

+1

이름을 속성으로 가져 오는 것이 더 직관적 일 수 있습니다. colnames = [curs.description의 desc에 대한 desc.name] – dexgecko

15

하려면 별도의 쿼리에서 열 이름, 당신은 INFORMATION_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 = [] 
    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)) 
0

난 당신의 쿼리 후 cursor.fetchone()를 사용해야 것으로 나타났습니다 : 데이터 행과 같은 쿼리

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

에 도착 열 이름, 당신은 커서의 설명 필드를 사용할 수 있습니다 cursor.description의 열 목록을 가져

-2
#!/usr/bin/python 
import psycopg2 
#note that we have to import the Psycopg2 extras library! 
import psycopg2.extras 
import sys 

def main(): 
    conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'" 
    # print the connection string we will use to connect 
    print "Connecting to database\n ->%s" % (conn_string) 

    # get a connection, if a connect cannot be made an exception will be raised here 
    conn = psycopg2.connect(conn_string) 

    # conn.cursor will return a cursor object, you can use this query to perform queries 
    # note that in this example we pass a cursor_factory argument that will 
    # dictionary cursor so COLUMNS will be returned as a dictionary so we 
    # can access columns by their name instead of index. 
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) 

    # tell postgres to use more work memory 
    work_mem = 2048 

    # by passing a tuple as the 2nd argument to the execution function our 
    # %s string variable will get replaced with the order of variables in 
    # the list. In this case there is only 1 variable. 
    # Note that in python you specify a tuple with one item in it by placing 
    # a comma after the first variable and surrounding it in parentheses. 
    cursor.execute('SET work_mem TO %s', (work_mem,)) 

    # Then we get the work memory we just set -> we know we only want the 
    # first ROW so we call fetchone. 
    # then we use bracket access to get the FIRST value. 
    # Note that even though we've returned the columns by name we can still 
    # access columns by numeric index as well - which is really nice. 
    cursor.execute('SHOW work_mem') 

    # Call fetchone - which will fetch the first row returned from the 
    # database. 
    memory = cursor.fetchone() 

    # access the column by numeric index: 
    # even though we enabled columns by name I'm showing you this to 
    # show that you can still access columns by index and iterate over them. 
    print "Value: ", memory[0] 

    # print the entire row 
    print "Row: ", memory 

if __name__ == "__main__": 
    main() 
1

I 알 ([desc[0] for desc in curs.description]에 즉) 그래서 비슷한 문제에 직면하는 데 사용됩니다. 이 문제를 해결하기 위해 간단한 트릭을 사용합니다. 당신이 원하는 경우 2.7

total_fields = len(cursor.description)  
fields_names = [i[0] for i in cursor.description 
    Print fields_names 
0

을 다음을 수행 할 수 있습니다 당신이 그런

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

같은 목록에 열 이름이 있다고 가정 db 쿼리에서 namedtuple obj를 사용하려면 다음 스 니펫을 사용할 수 있습니다.

from collections import namedtuple 

def create_record(obj, fields): 
    ''' given obj from db returns namedtuple with fields mapped to values ''' 
    Record = namedtuple("Record", fields) 
    mappings = dict(zip(fields, obj)) 
    return Record(**mappings) 

cur.execute("Select * FROM people") 
colnames = [desc[0] for desc in cur.description] 
rows = cur.fetchall() 
cur.close() 
result = [] 
for row in rows: 
    result.append(create_record(row, colnames)) 

이것은 그들이 클래스 속성이

등 record.id, record.other_table_column_name,

또는 짧은을 즉 것처럼 레코드 값을 당나귀 할 allowes

from psycopg2.extras import NamedTupleCursor 
with cursor(cursor_factory=NamedTupleCursor) as cur: 
    cur.execute("Select * ...") 
    return cur.fetchall() 
3

작성 파이썬 스크립트 다음 SQL 쿼리 쓰기를 실행 한 후

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

당신이 할 수있는 또 다른 일은 커서를 작성하여 이름으로 열을 참조 할 수있게하는 것입니다. 첫 번째 장소) :

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 
관련 문제