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

我的梦境 提交于 2020-08-10 05:16:15

问题


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?


回答1:


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



回答2:


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"])


来源:https://stackoverflow.com/questions/58854993/psycopg2-use-column-names-instead-of-column-number-to-get-row-data

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