问题
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