I am inserting a few thousand rows into a table with a UNIQUE constraint, using cursor.executemany()
. On some occasions the data may have a duplicate which violates the constraint, and sqlite
throws an IntegrityError
exception.
Is there any way to determine which row caused the violation?
Simplified code:
import sqlite3
conn = sqlite3.connect(':memory:')
#Create table
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS test(name TEXT,UNIQUE(name))')
data = [('Larry',),('Curly',),('Moe',),('Larry',)]
try:
cursor.executemany('INSERT INTO test VALUES(?)',data)
print('{0} rows inserted'.format(cursor.rowcount))
except sqlite3.IntegrityError as ie:
print('Exception:',ie)
Which results in:
Exception: UNIQUE constraint failed: test.name
as expected. But how can I identify that it was the duplicate 'Larry' row that violated the UNIQUE constraint? Or do I just have to insert the rows one at a time?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744746149a4591308.html
评论列表(0条)