[英]Python sqlite3 what happens if executemany() encounters an integrity error partway through?
If I run the SQL command如果我运行 SQL 命令
INSERT INTO my_table VALUES (?);
with the constraint与约束
CREATE my_table(
user_name VARCHAR(255) PRIMARY KEY
);
Using sqlite3's executemany()
command on a list ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'g', 'h', 'i']
, I'm going to get a sqlite3.IntegrityError
.在列表上使用 sqlite3 的
executemany()
命令['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'g', 'h', 'i']
,我将得到一个sqlite3.IntegrityError
。
I have a few questions about the behavior of executemany()
when it encounters this error, and I have been unable to find any documentation on the behavior.我对
executemany()
遇到此错误时的行为有一些疑问,我一直找不到有关该行为的任何文档。
1) Are the values inserted prior to the exception always intact? 1) 在异常之前插入的值是否始终完整?
2) Are there any cases in which values after the exception occurs might be inserted? 2) 是否有可能在异常发生后插入值的情况?
3) Is there any way to determine which value(s) cause an exception? 3)有什么方法可以确定哪些值导致异常? (The best I can think of is to wrap the list in a generator to track the state, log the problem entries, and retry on the rest of the generator until the entire list is consumed.)
(我能想到的最好的方法是将列表包装在生成器中以跟踪状态、记录问题条目,然后重试生成器的其余部分,直到整个列表都被消耗掉。)
The test script below provides some evidence:下面的测试脚本提供了一些证据:
Note that you can use a transaction if you want to prevent any values being inserted if an IntegrityError
occurs.请注意,如果您想在发生
IntegrityError
时防止插入任何值,则可以使用事务。 Example below.下面举例。 See also here for more.
另请参阅此处了解更多信息。
import sqlite3
conn = sqlite3.connect('del.db')
tuples = ('a','b','c','a','d')
conn.execute('create table test (col text primary key)')
conn.commit()
c = conn.cursor()
try:
c.executemany('insert into test values (?)', tuples)
except sqlite3.IntegrityError as exc:
print(exc)
c.close()
results = conn.execute('select * from test')
results.fetchall()
results in the following output导致以下输出
UNIQUE constraint failed: test.col
[('a',), ('b',), ('c',)]
Whereas if you use a transaction:而如果您使用事务:
c = conn.cursor()
c.execute('begin')
try:
c.executemany('insert into test values (?)', tuples)
except sqlite3.IntegrityError as exc:
c.execute('rollback')
No data is entered.没有输入数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.