I’m inserting values into my table (from python code) as follows:
cur.execute("insert into t(a, b, c) values (?, ?, ?)", (a, b, c))
There is a unique constraint on column c. What is a common way of insert if I want to cover the case when we’re inserting duplicate value for c column?
I have some ideas
- select everything from t to list and test before inserting if the value is already present
- try-catch block
- some more sophisticated sqlite statement
How would you test it?
thank you
You could use INSERT OR REPLACE to update rows with a unique constraint,
or INSERT OR IGNORE to ignore inserts which conflict with a unique constraint:
These sqlite commands are probably faster than writing Python code to do the same thing, though to test this you could use Python’s
timeitmodule to test the speed of various implementations. For example, you could runversus
versus