psycopg2.extras.DictCursor does not give me column names

一曲冷凌霜 提交于 2021-01-27 12:12:01

问题


I am using psycopg2 to access the data from the Postgres database. I am using psycopg2.extras.DictCursor for getting the data in a dict-like form using the following query:

try:
    self.con = psycopg2.connect(dbname=self.db, user=self.username, 
host=self.host, port=self.port)

cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor)

cur.execute("SELECT * FROM card")

result = cur.fetchall()

print result

I get the output as a list:

[['C01', 'card#1', 'description#1', '1'], ['C02', 'card#2', 'description#2', '1']]

However, I want the column names as well. I read another similar question here, but on trying the following I get a KeyError:

cur.execute("SELECT * FROM card")
for row in cur:
    print(row['column_name']) 

However, the following works:

cur.execute("SELECT * FROM card")
for row in cur:
    print(row['id'])

Output:

C01
C02

Any ideas on how I can get the column names as well?


回答1:


to get all column names you can use the mehtod keys for row item, for example:

cur.execute("SELECT * FROM card")
result = cur.fetchall()
keys = list(result[0].keys()) if result else []
for row in result:
    for key in keys:
        print(row[key])


来源:https://stackoverflow.com/questions/55628133/psycopg2-extras-dictcursor-does-not-give-me-column-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!