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

前端 未结 10 2062
清歌不尽
清歌不尽 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
    
    0 讨论(0)
  • 2020-12-12 12:33

    If you want to have a named tuple obj from db query you can use the following snippet:

    from collections import namedtuple
    
    def create_record(obj, fields):
        ''' given obj from db returns named tuple with fields mapped to values '''
        Record = namedtuple("Record", fields)
        mappings = dict(zip(fields, obj))
        return Record(**mappings)
    
    cur.execute("Select * FROM people")
    colnames = [desc[0] for desc in cur.description]
    rows = cur.fetchall()
    cur.close()
    result = []
    for row in rows:
        result.append(create_record(row, colnames))
    

    This allows you to access record values as if they were class properties i.e.

    record.id, record.other_table_column_name, etc.

    or even shorter

    from psycopg2.extras import NamedTupleCursor
    with cursor(cursor_factory=NamedTupleCursor) as cur:
       cur.execute("Select * ...")
       return cur.fetchall()
    
    0 讨论(0)
  • 2020-12-12 12:35
     # You can use this function
     def getColumns(cursorDescription):
         columnList = []
         for tupla in cursorDescription:
             columnList.append(tupla[0])
         return columnList 
    
    0 讨论(0)
  • 2020-12-12 12:37
    #!/usr/bin/python
    import psycopg2
    #note that we have to import the Psycopg2 extras library!
    import psycopg2.extras
    import sys
    
    def main():
        conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
        # print the connection string we will use to connect
        print "Connecting to database\n ->%s" % (conn_string)
    
        # get a connection, if a connect cannot be made an exception will be raised here
        conn = psycopg2.connect(conn_string)
    
        # conn.cursor will return a cursor object, you can use this query to perform queries
        # note that in this example we pass a cursor_factory argument that will
        # dictionary cursor so COLUMNS will be returned as a dictionary so we
        # can access columns by their name instead of index.
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    
        # tell postgres to use more work memory
        work_mem = 2048
    
        # by passing a tuple as the 2nd argument to the execution function our
        # %s string variable will get replaced with the order of variables in
        # the list. In this case there is only 1 variable.
        # Note that in python you specify a tuple with one item in it by placing
        # a comma after the first variable and surrounding it in parentheses.
        cursor.execute('SET work_mem TO %s', (work_mem,))
    
        # Then we get the work memory we just set -> we know we only want the
        # first ROW so we call fetchone.
        # then we use bracket access to get the FIRST value.
        # Note that even though we've returned the columns by name we can still
        # access columns by numeric index as well - which is really nice.
        cursor.execute('SHOW work_mem')
    
        # Call fetchone - which will fetch the first row returned from the
        # database.
        memory = cursor.fetchone()
    
        # access the column by numeric index:
        # even though we enabled columns by name I'm showing you this to
        # show that you can still access columns by index and iterate over them.
        print "Value: ", memory[0]
    
        # print the entire row 
        print "Row: ", memory
    
    if __name__ == "__main__":
        main()
    
    0 讨论(0)
提交回复
热议问题