Reputation: 539
I'm using python, psycopg2, and postgresql. Looking for a way to reference the column directly by name. See example below.
TABLE testtable
testcolumn1 | testcolumn2 | testcolumn3
------------+-------------+------------
horse | cow | goat
simple | code | test
cant | figure | this
conn = psycopg2.connect("dbname='test' user='me' password='pass'")
cursor = conn.cursor()
cursor.execute("select * from testtable")
cursor_rows = cursor.fetchall()
for row in cursor_rows:
print(row['testcolumn2'])
# the result of the loop should be
cow
code
figure
Is there a way to directly reference by column name like this?
Thank you for any help
Upvotes: 0
Views: 490
Reputation: 1729
Try using
import psycopg2.extras
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
Documentation here. There is also support for named tuples.
Upvotes: 2