您可以使用INSERT OR REPLACE 来更新具有唯一约束的行,
或INSERT OR IGNORE 忽略与唯一约束冲突的插入:
import sqlite3
def insert_or_replace():
# https://sqlite.org/lang_insert.html
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')
cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
cursor.execute('INSERT OR REPLACE INTO foo (bar,baz) VALUES (?, ?)',(1,3))
cursor.execute('SELECT * from foo')
data=cursor.fetchall()
print(data)
# [(1, 3)]
def on_conflict():
# https://sqlite.org/lang_insert.html
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')
cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
cursor.execute('INSERT OR IGNORE INTO foo (bar,baz) VALUES (?, ?)',(1,3))
cursor.execute('SELECT * from foo')
data=cursor.fetchall()
print(data)
# [(1, 2)]
insert_or_replace()
on_conflict()
这些 sqlite 命令可能比编写 Python 代码来做同样的事情要快,但要测试这一点,您可以使用 Python 的 timeit 模块来测试各种实现的速度。例如,您可以运行
python -mtimeit -s'import test' 'test.insert_or_replace()'
对
python -mtimeit -s'import test' 'test.filter_nonunique_rows_in_Python()'
对
python -mtimeit -s'import test' 'test.insert_with_try_catch_blocks()'