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

前端 未结 10 2061
清歌不尽
清歌不尽 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:14

    I have noticed that you must use cursor.fetchone() after the query to get the list of columns in cursor.description (i.e in [desc[0] for desc in curs.description])

    0 讨论(0)
  • 2020-12-12 12:21

    From "Programming Python" by Mark Lutz:

    curs.execute("Select * FROM people LIMIT 0")
    colnames = [desc[0] for desc in curs.description]
    
    0 讨论(0)
  • 2020-12-12 12:22

    If you're looking to get a pandas data frame with column headers already associated, try this:

    import psycopg2, pandas
    
    con=psycopg2.connect(
        dbname=DBNAME, 
        host=HOST, 
        port=PORT, 
        user=USER, 
        password=PASSWORD
    )
    
    sql = """
    select * from x
    """
    
    d = pandas.read_sql_query(sql,con)
    
    con.close()
    
    print(type(d))
    
    print(pandas.DataFrame.head(d))
    
    0 讨论(0)
  • 2020-12-12 12:27

    To get the column names in a separate query, you can query the information_schema.columns table.

    #!/usr/bin/env python3
    
    import psycopg2
    
    if __name__ == '__main__':
      DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'
    
      column_names = []
    
      with psycopg2.connect(DSN) as connection:
          with connection.cursor() as cursor:
              cursor.execute("select column_name from information_schema.columns where table_schema = 'YOUR_SCHEMA_NAME' and table_name='YOUR_TABLE_NAME'")
              column_names = [row[0] for row in cursor]
    
      print("Column names: {}\n".format(column_names))
    

    To get column names in the same query as data rows, you can use the description field of the cursor:

    #!/usr/bin/env python3
    
    import psycopg2
    
    if __name__ == '__main__':
      DSN = 'host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER'
    
      column_names = []
      data_rows = []
    
      with psycopg2.connect(DSN) as connection:
        with connection.cursor() as cursor:
          cursor.execute("select field1, field2, fieldn from table1")
          column_names = [desc[0] for desc in cursor.description]
          for row in cursor:
            data_rows.append(row)
    
      print("Column names: {}\n".format(column_names))
    
    0 讨论(0)
  • 2020-12-12 12:29

    After executing SQL query write following python script written in 2.7

    total_fields = len(cursor.description)    
    fields_names = [i[0] for i in cursor.description   
        Print fields_names
    
    0 讨论(0)
  • 2020-12-12 12:29

    I also used to face similar issue. I use a simple trick to solve this. Suppose you have column names in a list like

    col_name = ['a', 'b', 'c']
    

    Then you can do following

    for row in cursor.fetchone():
        print zip(col_name, row)
    
    0 讨论(0)
提交回复
热议问题