0

I have a database table place like below:

command_create_table = """CREATE TABLE if not exists place (
name VARCHAR(100),
lat DOUBLE(100, 10),
lng DOUBLE(100,10),
vicinity VARCHAR(100),
typeOfPlace VARCHAR(100));""

I want to insert into this table only if certain entry doesn't exist. But there is no such command like below.

cursor.execute("INSERT if not exists into place (name, lat, lng, vicinity, typeOfPlace) values (?, ?, ?, ?, ?)",(name, lat, lng, vicinity, typeOfPlace))

I tried making name as PRIMARY KEY in the place table and using command

cursor.execute("INSERT into place (name, lat, lng, vicinity, typeOfPlace) values (?, ?, ?, ?, ?)",(name, lat, lng, vicinity, typeOfPlace))

But getting error sqlite3.IntegrityError: UNIQUE constraint failed: place.name

What am I missing? Any suggestion?

nad
  • 2,640
  • 11
  • 55
  • 96
  • 1
    are you inserting twice the same `name` value? – raul.vila Apr 18 '18 at 18:03
  • 1
    `INSERT OR IGNORE INTO...` – roganjosh Apr 18 '18 at 18:03
  • Actually, yeah, you've not set any unique constraints on the table fields. – roganjosh Apr 18 '18 at 18:07
  • @roganjosh yes INSERT or IGNORE INTO .. is the answer. Add it as answer and I will mark it as the correct answer. – nad Apr 18 '18 at 18:19
  • I'm not sure exactly what that statement does if you don't set any constraints when you create that table. I think it might be grossly inefficient and I'm currently on a phone so can't test properly. I'll hold back from an answer for now. It's open to all to answer :) – roganjosh Apr 18 '18 at 19:09

0 Answers0