【问题标题】:psycopg2 use column names instead of column number to get row datapsycopg2 使用列名而不是列号来获取行数据
【发布时间】:2021-04-16 20:04:00
【问题描述】:

所以目前当我执行 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"])

这可能吗,如果可以,那该怎么做?

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    无需调用 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"])
    

    【讨论】:

    • 不知道。但这仍然不能回答我的问题,因为当我尝试使用 string 而不是 integer 来获取它抛出的 row 值和异常时。
    • @duško-mirković 是的,我的错,我写的太快了,忘记了将光标结果作为字典管理的代码部分。我编辑了我的答案。
    【解决方案2】:

    你需要使用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
    

    【讨论】:

    • 值得注意的是,如果传递了整数索引,RealDictCursor 将引发 KeyErrorpsycopg2.extras.DictCursor 接受字符串(列名)键和整数索引。
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2018-01-09
    • 2012-07-27
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多