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

后端 未结 2 1469
清歌不尽
清歌不尽 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: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"])
    

提交回复
热议问题