I am executing the following code, however, occasionally, a duplicate key violation would occur and the entire insert would stop. How to ignore such errors and let the query execute for the valid entries?
code:
query_data = ','.join(cur.mogrify('(%s,%s)', row) for row in data)
insert_q = "INSERT INTO <table> VALUES {0};".format(query_data)
try:
cur.execute(insert_q)
except psycopg2.Error:
self.logger.exception('Database error')
con.commit()
UPDATE 2:
I posted my own answer below which solved the problem. It uses the new ON CONFLICT syntax in Postgres.
UPDATE 1:
There was a problem about commiting inside the except block, however, what I found was, if you don't all the other inserts won't execute giving the following error:
ERROR: current transaction is aborted, commands ignored until end of transaction block
To avoid the confusion, added the commit after the try except