Skip to content

Instantly share code, notes, and snippets.

@aveek22
Created December 25, 2020 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aveek22/32b5487838605700fe37afdb48f9b575 to your computer and use it in GitHub Desktop.
Save aveek22/32b5487838605700fe37afdb48f9b575 to your computer and use it in GitHub Desktop.
This file exports data from pandas to a table in PostgreSQL database.
import pandas as pd
import sqlalchemy
# Create the engine to connect to a PostgreSQL database
engine = sqlalchemy.create_engine('postgresql://aveek:test1234@localhost:5432/sql-shack-demo')
# Read data from the SQL Table
data = pd.read_csv('superstore.csv')
# Print first few rows of the dataframe
print(data.head())
#######################################################################################
# Write the data into a table in PostgreSQL Database
data.to_sql(name = 'superstore',
con = engine,
if_exists='append',
index = False,
chunksize = 1000,
dtype = {
"Row_ID" : sqlalchemy.types.Integer,
"Order_ID" : sqlalchemy.types.Text,
"Order_Date" : sqlalchemy.types.DateTime,
"Ship_Date" : sqlalchemy.types.DateTime,
"Sales" : sqlalchemy.types.Numeric,
"Quantity" : sqlalchemy.types.Integer,
"Discount" : sqlalchemy.types.Numeric,
"Profit" : sqlalchemy.types.Numeric,
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment