Connecting to Redshift using Python

Hi,
I have been exploring Python recently as a part of doing my Masters in Data Science and I must says , its really a powerful tool and the possibilities are endless using Python. Recently we had a project to connect to Amazon Redshift and was having issues using ODBC and adapter. I was exploring on the possibility of using Python and its amazing that you can achieve the task with 10 lines of code.

Below is the code to achieve connectivity

#Import Packages required to setup connection
import pandas as pd
from sqlalchemy import create_engine

# setting up connection

connection=’postgresql://<username>:<password>@<server_name>:port/schema’
engine = create_engine(connection)
#Connecting and saving file as csv
with engine.connect() as conn, conn.begin():
df = pd.read_sql(“””
select * from table ;”””, conn)
df.to_csv(“path\filename.csv”)
conn.close();
Once you executed the script above after tweaking the connection variable . You should see a file in the path defined on the second last step.

 

Till next time

Cheers!!

Jethin Abraham

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s