为了防止我的数据库变得太大,我希望 sqlite 只插入尚未插入的值。我做了一些搜索,并认为最好的方法是使用 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]
Change INSERT
to INSERT OR IGNORE
:
cur.execute('INSERT OR IGNORE INTO oldposts VALUES(?)', [submID])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)