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

标签 python transactions insert sqlite

我正在尝试使用插入在 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')

然而,这似乎并没有什么不同。一种提高插入速度的方法将不胜感激。

最佳答案

根据 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')

关于python - 将插入合并到一个事务中 Python SQLite3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5055314/

相关文章:

python - 如何对许多对象使用 bulk_create() 来执行 save() 操作

jdbc - 无法从 PoolingDataSource 的池中获取连接

php - MySQL 插入问题 - 在本地计算机上有效,但在服务器上无效,无论权限如何

php - PHP 中的转义字符和保留

python - 当我尝试运行 Odoo 时,为什么会出现错误 "Name node can' t be use with 'None' Constant”?

python - Python:如何将两个有符号的int16数组求和成一个而不会溢出

python - 使用 cmake 构建 Python 共享对象绑定(bind),这取决于外部库

python - Requests SSLError : HTTPSConnectionPool(host ='www.recruit.com.hk' , port=443): 超过 url 的最大重试次数

transactions - 域对象身份重用 vs 新建

PHP 插入不起作用