简体   繁体   中英

Write data from csv to Postgres using Python and overwrite existing rows

I am currently exporting a csv file to a Postgres database, however if I do this operation multiple times, the same rows happen to be duplicated in the database.

How can I modify my code to overwrite existing rows to avoid duplication?

with open('file1.csv', 'r') as f:
    next(f)
    cur.copy_from(f, 'table1', sep=',')
            
conn.commit()

You cannot do that with COPY .

You could use INSERT... ON CONFLICT , but that necessitates that you create a unique constraint or index that defines what you mean by "duplicate".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM