In pysqlite, violating a NOT NULL
or a UNIQUE
constraint likewise raise an IntegrityError.
Unfortunately, this Exception type does not provide an error code, but only a message.
So, let's say I want to ignore unique-constraint violations, because I know this is safe on the given data, but Null values in the key columns should be reported.
I've come up with the following solution:
con = sqlite3.connect(':MEMORY:')
con.execute('''CREATE TABLE ABCD (A TEXT NOT NULL,
B TEXT NOT NULL,
C TEXT NOT NULL,
D TEXT NOT NULL,
PRIMARY KEY (A, B))''')
with con:
for a, b, c, d in inputs:
try:
con.execute('INSERT INTO ABCD VALUES (?, ?, ?, ?)',
(a, b, c, d))
except sqlite3.IntegrityError as e:
# Skip 'not unique' errors, but raise others.
if not e.message.endswith('not unique'):
raise
con.close()
However, parsing the error message seems wrong and might be unreliable.
Is there a better way to do this, maybe even using con.executemany()
?
(A, B)
is you PK. I think that this constraint must not be ignored. What would be a real world use case? – MuricateINSERT OR IGNORE
then. – Abridgment