psycopg2.extras.DictCursor 没有给我列名 [英] psycopg2.extras.DictCursor does not give me column names
本文介绍了psycopg2.extras.DictCursor 没有给我列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 psycopg2 访问来自 Postgres 数据库的数据.我正在使用 psycopg2.extras.DictCursor 使用以下查询以类似 dict 的形式获取数据:
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
我将输出作为列表:
[['C01', 'card#1', 'description#1', '1'], ['C02', 'card#2', 'description#2', '1']]
但是,我也想要列名.我阅读了另一个类似的问题here,但在尝试以下我得到KeyError:
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'])
但是,以下有效:
cur.execute("SELECT * FROM card")
for row in cur:
print(row['id'])
输出:
C01
C02
关于如何获取列名的任何想法?
Any ideas on how I can get the column names as well?
推荐答案
要获取所有列名,您可以使用 mehtod keys
为行项,例如:
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])
这篇关于psycopg2.extras.DictCursor 没有给我列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文