You can use INSERT OR REPLACE to update rows with a unique constraint, or INSERT OR IGNORE to ignore inserts that conflict with a unique constraint:
import sqlite3 def insert_or_replace():
These sqlite commands are probably faster than writing Python code to do the same, although you can use the Python timeit module to check the speed of various implementations to verify this. For example, you can run
python -mtimeit -s'import test' 'test.insert_or_replace()'
against
python -mtimeit -s'import test' 'test.filter_nonunique_rows_in_Python()'
against
python -mtimeit -s'import test' 'test.insert_with_try_catch_blocks()'
source share