Skip to content

Instantly share code, notes, and snippets.

@kunanit
Created April 24, 2017 14:36
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kunanit/eb0723eef653788395bb41c661c1fa86 to your computer and use it in GitHub Desktop.
Save kunanit/eb0723eef653788395bb41c661c1fa86 to your computer and use it in GitHub Desktop.
Read postgres database table into pandas dataframe
import pandas as pd
from sqlalchemy import create_engine
# follows django database settings format, replace with your own settings
DATABASES = {
'production':{
'NAME': 'dbname',
'USER': 'user',
'PASSWORD': 'pass',
'HOST': 'rdsname.clqksfdibzsj.us-east-1.rds.amazonaws.com',
'PORT': 5432,
},
}
# choose the database to use
db = DATABASES['production']
# construct an engine connection string
engine_string = "postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}".format(
user = db['USER'],
password = db['PASSWORD'],
host = db['HOST'],
port = db['PORT'],
database = db['NAME'],
)
# create sqlalchemy engine
engine = create_engine(engine_string)
# read a table from database into pandas dataframe, replace "tablename" with your table name
df = pd.read_sql_table('tablename',engine)
@jeffshek
Copy link

Thanks for this, it was super helpful!

@johnplt
Copy link

johnplt commented Mar 9, 2021

Thanks for that useful code ;)

@kayode77
Copy link

This is great, thanks

@puddlejumper90
Copy link

This is incredible, thank you so much for this!

@yukamara
Copy link

Thanks so much for this code, very helpful :)

@ajinzrathod
Copy link

Worked as a charm

@gautam-dwivedi
Copy link

Thanks a lot for the code

@vshinde-medacist
Copy link

Thanks @kunanit for the code.

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