我想要一個通用的方法來直接從選定的列名稱生成列標籤,並回想一下,看到python的psycopg2模塊支持此功能。如何從psycopg2遊標獲取列名稱列表?
69
A
回答
116
從「編程的Python」由馬克·魯茨:
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 = []
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))
0
我注意到,你必須在查詢後使用cursor.fetchone()
獲得cursor.description
列的列表(即[desc[0] for desc in curs.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
我人所以曾經面臨類似的問題。我用一個簡單的技巧來解決這個問題。 假設你像
col_name = ['a', 'b', 'c']
然後列表有列名,你可以做以下
for row in cursor.fetchone():
print zip(col_name, row)
0
執行SQL查詢寫下面寫在2.7
total_fields = len(cursor.description)
fields_names = [i[0] for i in cursor.description
Print fields_names
3
如果你想python腳本後從db查詢命名爲obj 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))
這allowes你,好像他們是類屬性,即
record.id,record.other_table_column_name等
,甚至更短的以評估記錄值
from psycopg2.extras import NamedTupleCursor
with cursor(cursor_factory=NamedTupleCursor) as cur:
cur.execute("Select * ...")
return cur.fetchall()
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. 從列表中獲取列名稱
- 2. 如何獲取datagridvier列標題名稱
- 3. SQLAlchemy從列中獲取標籤名稱
- 4. 如何獲取隊列名稱NServiceBus從
- 5. 如何從SharePoint列表中獲取列名稱?
- 6. 如何從列表中獲取選定列名稱
- 7. 從AbstractTableModel獲取列名稱
- 8. LINQ:獲取表列名稱
- 9. 從完整url獲取列表名稱
- 10. 如何獲取Android列表視圖中的列表名稱?
- 11. SQLAlchemy從表和列名稱中獲取屬性名稱
- 12. 如何從模型列表中獲取每個值名稱
- 13. 如何從地理編碼中獲取地區名稱列表
- 14. 如何從mangled名稱獲取方法參數列表?
- 15. SharePoint 2007:如何使用Web服務從列表名稱獲取列表URL?
- 16. 新來的NoSQL,如何從ID列表獲取類別名稱的列表
- 17. 從空表中獲取列名列表
- 18. 如何使用列名稱從系列獲取值?
- 19. 如何獲取sqlite3/iPhone上的列名稱列表?
- 20. 如何使用Sqlite.swift獲取列名稱的列表?
- 21. 如何獲取sqlserver中的序列名稱列表?
- 22. 如何獲取Postgres中的序列名稱列表?
- 23. GCD獲取隊列名稱/標籤
- 24. 獲取列的標題名稱
- 25. 從表中獲取列名
- 26. 如何從Button獲取標籤名稱?
- 27. 使用.net獲取名稱表,名稱列,名稱數據
- 28. 從Facebook陣列獲取名稱列表的Facebook?
- 29. 從sharepoint列表中獲取所有列名稱java
- 30. 使用Linq,我如何從GridView獲取列名列表?從DataTable?
如果您只是想要列名稱,請不要選擇表中的所有行。這是更有效的:'curs.execute(「SELECT * FROM people LIMIT 0」)' – Demitri 2012-09-06 22:03:46
值得一提的是,這對視圖和表格都有效,但它不能(很容易)從視圖獲取列名'information_schema'。 – wjv 2016-06-23 07:30:18
可能更直觀地得到名稱作爲屬性: colnames = [des.desc.name用於des.c in curs.description] – dexgecko 2018-01-15 23:28:52