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

后端 未结 2 1440
清歌不尽
清歌不尽 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
    

提交回复
热议问题