sqlite3,IntegrityError:插入值时UNIQUE约束失败

时间:2016-04-09 15:09:46

标签: python-3.x sqlite

为了防止我的数据库变得太大,我希望sqlite只插入尚未插入的值。我做了一些搜索,并认为最好的方法是使用UNIQUE约束。在我看来,当插入一个非UNIQUE的值时,sqlite会崩溃,我该如何规避这个错误并继续下一次提交呢?

以下是一些相关代码。

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()

这是追溯:

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]

2 个答案:

答案 0 :(得分:11)

INSERT更改为INSERT OR IGNORE

cur.execute('INSERT OR IGNORE INTO oldposts VALUES(?)', [submID])

答案 1 :(得分:0)

将“INSERT”更改为“INSERT OR REPLACE” 它更好......

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()