Skip to content

Instantly share code, notes, and snippets.

@sebastien-collet
Created October 12, 2017 12:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sebastien-collet/debde11f96c8bd5dc5544ce4c7a418c1 to your computer and use it in GitHub Desktop.
Save sebastien-collet/debde11f96c8bd5dc5544ce4c7a418c1 to your computer and use it in GitHub Desktop.
import pandas as pd
from sqlalchemy import create_engine
# ====== Connection ======
# Connecting to PostgreSQL by providing a sqlachemy engine
engine = create_engine('postgresql://'+os.environ['POSTGRESQL_USER']+':'+os.environ['POSTGRESQL_PASSWORD']+'@'+os.environ['POSTGRESQL_HOST_IP']+':'+os.environ['POSTGRESQL_PORT']+'/'+os.environ['POSTGRESQL_DATABASE'],echo=False)
# ====== Writing table ======
# Creating a simple pandas DataFrame with two columns
liste_hello = ['hello1','hello2']
liste_world = ['world1','world2']
df = pd.DataFrame(data = {'hello' : liste_hello, 'world': liste_world})
# Writing Dataframe to PostgreSQL and replacing table if it already exists
df.to_sql(name='helloworld', con=engine, if_exists = 'replace', index=False)
# ====== Reading table ======
# Reading PostgreSQL table into a pandas DataFrame
data = pd.read_sql('SELECT * FROM helloworld', engine)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment