因此,当前,当我执行SELECT查询并检索数据时,我必须获得如下结果:
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])
我想做的是,使用列名而不是整数,像这样:
for row in users:
print(row["id"])
print(row["first_name"])
print(row["last_name"])
有可能吗?如果可以,怎么办?
答案 0 :(得分:1)
您需要使用RealDictCursor,然后才能像字典一样访问结果:
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'])
输出:
[RealDictRow([('user', 'dbAdmin')])]
dbAdmin
答案 1 :(得分:0)
无需调用fetchall()方法,psycopg2游标是可以直接执行的可迭代对象:
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"])