Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3, IntegrityError: UNIQUE constraint failed when inserting a value

In order to prevent my database from growing too large I want sqlite only to insert values that has not yet been inserted. I've done some searching and figured the best way to do so was to use a UNIQUE constraint. It seems to me that that sqlite crashes when inserting a value that is not UNIQUE, how do I circumvent this error and continue with the next submission?

Below is some relevant code.

sql = sqlite3.connect('submissions.db')
cur = sql.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS some_table(id TEXT UNIQUE)')
sql.commit()

for thing in things:
    try:
        # Do some stuff
    except AttributeError:
        pass

    cur.execute('INSERT INTO some_table VALUES(?)', [thing])
    sql.commit()

Here is the traceback:

Traceback (most recent call last):
  File "D:\Directory\Python\Projects\Oddshotcrawler for Reddit, globaloffensive\oddshotcrawler.py", line 62, in <module>
    oddshotcrawler()
  File "D:\Directory\Python\Projects\Oddshotcrawler for Reddit, globaloffensive\oddshotcrawler.py", line 54, in oddshotcrawler
    cur.execute('INSERT INTO oldposts VALUES(?)', [thing])
sqlite3.IntegrityError: UNIQUE constraint failed: some_table.id
[Finished in 7.1s with exit code 1]
like image 559
kluvin Avatar asked Apr 09 '16 15:04

kluvin


People also ask

How do you resolve unique constraint failure?

If you want SQL to IGNORE that error and continue adding other records , then do this : INSERT or IGNORE into tablename VALUES (value1,value2 , so on ); If you want to replace the values in the table whenever the entry already exists , then do this: INSERT or REPLACE into tablename VALUES (value1,value2 , so on );

What does it mean by unique constraint failed?

Once a UNIQUE constraint is defined, if you attempt to insert or update a value that already exists in the column, SQLite will issue an error and abort the operation.

What is constraint in SQLite?

Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. Constraints could be column level or table level.


2 Answers

Change INSERT to INSERT OR IGNORE:

cur.execute('INSERT OR IGNORE INTO oldposts VALUES(?)', [submID])
like image 73
Colonel Thirty Two Avatar answered Sep 28 '22 02:09

Colonel Thirty Two


Change "INSERT" to "INSERT OR REPLACE" it's better...

Update_Table = """INSERT OR REPLACE INTO station_statusDB VALUES(?, ?, ?, ?);"""
with sql.connect(station_statusDB) as Conn:
    print("Connected to:", station_statusDB)
    Conn.execute(New_Station_Table)
    while Client_Flag != 0:
        print("Updating Station Database...")
        Conn.execute(Update_Table, (ClientID, Client_date, Client_Alarm, Client_Water))
        print("Done!, Saving...")
        Conn.commit()
like image 40
Sharon Zak Avatar answered Sep 28 '22 02:09

Sharon Zak