Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example on how to connect to redshift using psycopg2
__author__ = 'fbaldo'
import psycopg2
import pprint
configuration = { 'dbname': 'database_name',
'user':'user_name',
'pwd':'user_password',
'host':'redshift_endpoint',
'port':'redshift_password'
}
def create_conn(*args,**kwargs):
config = kwargs['config']
try:
conn=psycopg2.connect(dbname=config['dbname'], host=config['host'], port=config['port'], user=config['user'], password=config['pwd'])
except Exception as err:
print err.code, err
return conn
def select(*args,**kwargs):
# need a connection with dbname=<username>_db
cur = kwargs['cur']
try:
# retrieving all tables in my search_path
cur.execute("""select tablename from pg_table_def""")
except Exception as err:
print err.code,err
rows = cur.fetchall()
for row in rows:
print row
print 'start'
conn = create_conn(config=configuration)
cursor = conn.cursor()
print 'start select'
select(cur=cursor)
print 'finish'
cursor.close()
for n in conn.notices():
pprint(n)
conn.close()
@asevans48

This comment has been minimized.

Copy link

@asevans48 asevans48 commented Sep 24, 2020

you have an error in your config 'port':'redshift_password'

@NikhilCT

This comment has been minimized.

Copy link

@NikhilCT NikhilCT commented Oct 10, 2020

Hi, jaychoo,

Thanks for the code post.
I have on small doubt here, I'm not getting the table headers in output but getting table data. How we need to get the table headers.?

Thanks & Regards,
Nikhil

@iangelino

This comment has been minimized.

Copy link

@iangelino iangelino commented May 11, 2021

Help me please. I don't know how to write the syntax inside the cur.execute. exe to call a table. do you have any example? Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment