1 | initial version |
import pandas as pd
import psycopg2
from sqlalchemy import create_engine
df = pd.read_csv('your_file.csv')
conn = psycopg2.connect(
database="your_database_name",
user="your_username",
password="your_password",
host="your_host",
port="your_port"
)
engine = create_engine('postgresql+psycopg2://{0}:{1}@{2}/{3}'.format(
"your_username",
"your_password",
"your_host",
"your_database_name")
)
to_sql
method and specifying the engine, the table name, and the if_exists
parameter set to append or replace, depending on your needs:df.to_sql('your_table_name', engine, if_exists='append', index=False)
Note that you may also want to specify the data types for each column in the to_sql
call, using the dtype
parameter. This is particularly useful when dealing with timestamp data, in order to maintain the correct timezone information in the database.