简体   繁体   中英

psycopg2 use column names instead of column number to get row data

So currently when I execute SELECT query and retrieve data I have to get results like this:

connection = psycopg2.connect(user="admin",
                              password="admin",
                              host="127.0.0.1",
                              port="5432",
                              database="postgres_db")
cursor = connection.cursor()

cursor.execute("SELECT * FROM user")
users = cursor.fetchall() 

for row in users:
    print(row[0])
    print(row[1])
    print(row[2])

What I want to do is, use column names instead of integers, like this:

for row in users:
    print(row["id"])
    print(row["first_name"])
    print(row["last_name"])

Is this possible, and if it is, then how to do it?

You need to use RealDictCursor, then you can access the results like a dictionary:

import psycopg2
from psycopg2.extras import RealDictCursor
connection = psycopg2.connect(user="...",
                              password="...",
                              host="...",
                              port="...",
                              database="...",
                              cursor_factory=RealDictCursor)
cursor = connection.cursor()

cursor.execute("SELECT * FROM user")
users = cursor.fetchall()

print(users)
print(users[0]['user'])

Output:

[RealDictRow([('user', 'dbAdmin')])]
dbAdmin

no need to call fetchall() method, the psycopg2 cursor is an iterable object you can directly do:

cursor.execute("SELECT * FROM user")

for buff in cursor:
    row = {}
    c = 0
    for col in cursor.description:
        row.update({str(col[0]): buff[c]})
        c += 1

    print(row["id"])
    print(row["first_name"])
    print(row["last_name"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM