선택한 열 이름에서 직접 열 레이블을 생성하는 일반적인 방법을 원합니다. 파이썬의 psycopg2 모듈이이 기능을 지원한다는 것을 상기하십시오. 마크 루츠에 의해 "프로그래밍 파이썬"에서psycopg2 커서에서 열 이름 목록을 얻으려면 어떻게합니까?
69
A
답변
116
:
curs.execute("Select * FROM people")
colnames = [desc[0] for desc in curs.description]
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
관련 문제
- 1. 런타임에 ADM2 개체의 이름 또는 이름 목록을 얻으려면 어떻게합니까?
- 2. 파일 이름 목록을 작성하려면 어떻게합니까?
- 3. 시스템 트레이에있는 활성 아이콘 목록을 얻으려면 어떻게합니까?
- 4. Localizable.strings 파일이있는 언어 목록을 얻으려면 어떻게합니까?
- 5. ActiveMQ 브로커에서 주제 목록을 얻으려면 어떻게합니까?
- 6. 프로토콜이 정의하는 함수 목록을 얻으려면 어떻게합니까?
- 7. Active Directory에서 Organizational Units 목록을 얻으려면 어떻게합니까?
- 8. intalled RPM에서 라이센스 목록을 얻으려면 어떻게합니까?
- 9. 지원 파일에있는 PNG 이름 목록을 얻으려면 어떻게해야합니까?
- 10. VB.NET에서 실행중인 프로세스 이름 목록을 얻으려면 어떻게해야합니까?
- 11. psycopg2.extras.RealDictCursor를 사용하는 동안 열 순서를 유지하는 방법
- 12. 네트워크에서 사용할 수있는 SQL Server 목록을 얻으려면 어떻게합니까?
- 13. Oracle에서 패키지 내에 정의 된 유형 목록을 얻으려면 어떻게합니까?
- 14. 타임 스탬프 열이없는 데이터베이스의 테이블 목록을 얻으려면 어떻게합니까?
- 15. SQL Server 데이터베이스에서 수정 된 레코드 목록을 얻으려면 어떻게합니까?
- 16. 로그인 한 로컬 Windows 사용자 목록을 얻으려면 어떻게합니까?
- 17. 클래스를 인스턴스화하지 않고 클래스 멤버의 전체 목록을 얻으려면 어떻게합니까?
- 18. 비트 맵의 모든 16 진수 색상 목록을 얻으려면 어떻게합니까?
- 19. 내 Facebook 페이지를 좋아하는 사용자 목록을 얻으려면 어떻게합니까?
- 20. Active Directory에서 특정 부서에 속한 모든 사용자의 목록을 얻으려면 어떻게합니까?
- 21. 관리자가없는 SQL Server 인스턴스에서 데이터베이스 목록을 얻으려면 어떻게합니까?
- 22. 알려진 프록시 IP 주소의 집합 목록을 얻으려면 어떻게합니까?
- 23. pygtk를 사용하여 gnome2 데스크탑의 모든 창 목록을 얻으려면 어떻게합니까?
- 24. .Net 응용 프로그램의 모든 스레드 목록을 얻으려면 어떻게합니까?
- 25. PHP 함수에서 사용할 수있는 인수 목록을 얻으려면 어떻게합니까?
- 26. Java에서 신뢰할 수있는 루트 인증서 목록을 얻으려면 어떻게합니까?
- 27. ODBC 연결에서 사용 가능한 테이블 목록을 얻으려면 어떻게합니까?
- 28. 런타임에 프로젝트에 정의 된 클래스 목록을 얻으려면 어떻게합니까?
- 29. Visual Studio 프로젝트에서 사용되는 모든 클래스와 메서드 목록을 얻으려면 어떻게합니까?
- 30. PDO를 사용하여 PHP에서 MySQL 데이터베이스 목록을 얻으려면 어떻게합니까?
열 이름 만 원할 경우 테이블의 모든 행을 선택하지 마십시오. 이것은보다 효율적이다 :'curs.execute ("SELECT * FROM people LIMIT 0")' – Demitri
뷰의 컬럼 이름을 얻는 것이 쉽지만 'information_schema'. – wjv
이름을 속성으로 가져 오는 것이 더 직관적 일 수 있습니다. colnames = [curs.description의 desc에 대한 desc.name] – dexgecko