最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论