How to Python PostgreSQL INSERT IF NOT EXIST?

3.1k views Asked by At

I have a python script that is using the Psycopg adapter; I am parsing a JSON Array and inserting into my PostgreSQL database.

for item in data["SchoolJSONData"]:
mId = item.get("Id")
mNumofRooms = item.get("NumofRooms")
mFloors = item.get("Floors")

con = None
con = psycopg2.connect("dbname='database' user='dbuser'")
cur = con.cursor()
cur.execute('INSERT INTO Schools(Id, NumofRooms, Floors)VALUES(%s, %s, %s)',(mId, mNumofRooms, mFloors))
con.commit()

Everytime I run the script again, I get the following:

psycopg2.IntegrityError: duplicate key value violates unique constraint "schools_pkey"  

How can I run the insert script so that it will ignore existing entries in the database?

EDIT: Thanks for the replies all... I am trying to NOT overwrite any data, only ADD (if the PK is not already in the table), and ignore any errors. In my case I will only be adding new entries, never updating data.

1

There are 1 answers

1
Jay Kumar R On

There is no single one way to solve this problem. As well this problem has little to do with python. It is valid exception generated by the database ( not just postgre all databases will do the same ).

But you can try - catch this exception and continue smoothly later. OR
you can use "select count(*) where id = mId" to ensure it is not existing already.