将插入合并到一个事务Python SQLite3中

2024-04-19 13:04:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用insert在SQLite3上输入1000行,但是插入的时间太长了。我听说如果将插入合并到一个事务中,速度会大大提高。但是,我似乎不能让SQlite3跳过检查文件是否写在硬盘上。

这是一个样本:

if repeat != 'y':
    c.execute('INSERT INTO Hand (number, word) VALUES (null, ?)', [wordin[wordnum]])
    print wordin[wordnum]

data.commit()

这是我一开始就有的。

data = connect('databasenew')
data.isolation_level = None
c = data.cursor()  
c.execute('begin')

然而,这似乎没有什么不同。一种提高插入速度的方法将非常受欢迎。


Tags: 文件executedataif时间事务sqlite3速度
3条回答

(以防有人还在寻找答案)

如果只是连续执行1000次插入,则应该使用executemany。

What is the optimized way to insert large number of records (more than 40,000) in sqlite3

我刚刚与许多(订单数百万)的执行挣扎了大约30分钟才完成-切换到执行,我现在有大约10分钟的时间。

根据Sqlite文档,BEGIN事务应该以COMMIT结束

Transactions can be started manually using the BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command. But a transaction will also ROLLBACK if the database is closed or if an error occurs and the ROLLBACK conflict resolution algorithm is specified. See the documentation on the ON CONFLICT clause for additional information about the ROLLBACK conflict resolution algorithm.

所以,你的代码应该是这样的:

data = connect('databasenew')
data.isolation_level = None
c = data.cursor()  
c.execute('begin')

if repeat != 'y':
    c.execute('INSERT INTO Hand (number, word) VALUES (null,?)', [wordin[wordnum]])
    print wordin[wordnum]

    data.commit()

    c.execute('commit')

https://stackoverflow.com/a/3689929/1147726回答问题。execute('begin')没有任何效果。显然,connection.commit()就足够了。

相关问题 更多 >