python - Determining which row causes IntegrityError exception when using cursor.executemany() to insert data - Stack Overflow

I am inserting a few thousand rows into a table with a UNIQUE constraint, using cursor.executemany(). O

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信