Home > Back-end >  Don't overwrite data when I upload new using pandas dataframe and postgressql
Don't overwrite data when I upload new using pandas dataframe and postgressql

Time:08-26

I want to start uploading data to my PostgresSql table using pandas. I do the following,

import psycopg2
import pandas as pd
from sqlalchemy import create_engine

user = 'aaa'
passw= 'bbb'
host = 'ccc'
database = 'ddd'
conn_string = f'postgresql://{user}:{passw}@{host}/{database}'

df = pd.read_csv('20220817.csv')

db = create_engine(conn_string)
conn = db.connect()

table = 'tableTest'
df.to_sql(table, con=conn, if_exists='replace', index=False)

conn.close()

The problem is with this code I overwrite the previous data on my table. How can I upload new, without overwriting? I have if_exists=True but my new data is not the same because are time series and change the date and value.

Thank you!

CodePudding user response:

You can try by appending as follows:

df.to_sql(table, con=conn, if_exists='append', index=False)

Resource: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html

CodePudding user response:

Replace the argument if_exists='replace' to if_exists='append'

  • Related