1

I have a CSV file that I want to import do my postgresql database using Python. My current python code is:

import psycopg2

conn = psycopg2.connect("host=localhost dbname=db_name user=postgres password=******")
cur = conn.cursor()
with open(r'C:\Users\admin\Desktop\test.csv', 'r') as f:
    next(f)
    cur.copy_from(f, 'tms.data', sep='|', null='NULL')
conn.commit()

It worked perfectly to import new data, but if there is a row that already exists in the database it stops executing because of my primary key constraint. I´d like it to update the entire row if the data from that CSV row already exists and continues to insert/update the rest. Is there a way to do it using cursor.copy_from or copy_expert?

Thanks in advance :)

  • copy it into a temporary table and then insert from the temporary table into your existing table, using INSERT... ON CONFLICT. – Jeremy Dec 14 '20 at 19:18
  • Thanks! I´ll try using a temp table and the logic from the other questions that was commented here. – André Scattolin Dec 14 '20 at 19:46

0 Answers0