How do I get a list of column names from a psycopg2 cursor?

前端 未结 10 2064
清歌不尽
清歌不尽 2020-12-12 11:49

I would like a general way to generate column labels directly from the selected column names, and recall seeing that python\'s psycopg2 module supports this feature.

10条回答
  •  失恋的感觉
    2020-12-12 12:33

    Another thing you can do is to create a cursor with which you will be able to reference your columns by their names (that's a need which led me to this page in the first place):

    import psycopg2
    from psycopg2.extras import RealDictCursor
    
    ps_conn = psycopg2.connect(...)
    ps_cursor = psql_conn.cursor(cursor_factory=RealDictCursor)
    
    ps_cursor.execute('select 1 as col_a, 2 as col_b')
    my_record = ps_cursor.fetchone()
    print (my_record['col_a'],my_record['col_b'])
    
    >> 1, 2
    

提交回复
热议问题