0

How can I retrieve the data (including column names) from Amazon Redshift?

!pip install psycopg2-binary 

import psycopg2
import numpy as np
import pandas as pd

connection = psycopg2.connect(
    host=conn['host'],
    database=conn['database'],
    user=conn['user'],
    password=conn['password'],
    sslmode=conn['sslmode'],
    port= conn['port'])

cursor = connection.cursor() 
cursor.execute("SELECT * FROM <schema>.<table> LIMIT 5;")
data = np.array(cursor.fetchall()) 
cursor.close()
connection.close()

df = pd.DataFrame(data=data, )
df.head()

My current approach retrieves the data correctly but misses the header of the table, i.e. the column names. I know how to achieve this with sqlalchemy-redshift I would like to know whereas using plain Psycopg this is also possible.

G. Macia
  • 1,204
  • 3
  • 23
  • 38
  • 3
    Read the docs [Psycopg2](https://www.psycopg.org/docs/). I while give you a couple of shortcuts to relevant parts of docs. [Cursor](https://www.psycopg.org/docs/cursor.html) `description`. [Dict cursors](https://www.psycopg.org/docs/extras.html#connection-and-cursor-subclasses) – Adrian Klaver Jan 11 '21 at 20:55
  • I found the solution here https://stackoverflow.com/questions/55628133/psycopg2-extras-dictcursor-does-not-give-me-column-names – G. Macia Jan 12 '21 at 16:41

0 Answers0