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

后端 未结 2 1437
清歌不尽
清歌不尽 2021-01-21 02:53

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

connection = psycopg2.connect(user=\"admin\",
                                


        
相关标签:
2条回答
  • 2021-01-21 03:23

    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
    
    0 讨论(0)
  • 2021-01-21 03:43

    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"])
    
    0 讨论(0)
提交回复
热议问题