SQLite批量插入效率

本文探讨了SQLite数据库在批量插入数据时的效率问题,通过使用事务、预编译执行和调整写同步设置来提升性能。实验表明,使用事务和预编译能显著减少插入时间,关闭写同步虽然能加速但可能牺牲安全性。
摘要由CSDN通过智能技术生成

一、循环单条数据插入

SQLite插入单条数据效率并不高,原因是:

Because it does not have a central server to coordinate access, SQLite must close and reopen the database file, and thus invalidate its cache, for each transaction. In this test, each SQL statement is a separate transaction so the database file must be opened and closed and the cache must be flushed 1000 times. 

因为它没有中央服务器来协调访问,所以SQLite必须为每个事务关闭并重新打开数据库文件,从而使其缓存无效。在这个测试中,每个SQL语句都是一个独立的事务,因此必须打开和关闭数据库文件,并且必须刷新缓存1000次。

插入 1000 条数据测试:

const static char * insert_record_static = "INSERT INTO tbl_test (a, b, c) VALUES (1, 1, 1);";
// 1、循环插入 1000 条数据
t_start = clock();
for(int i = 0; i < 1000; i++)
{
    sqlite3_exec(db, insert_record_static, NULL, NULL, &err);
}
t_stop = clock();
std::cout << "Insert static 1000 cost time " << (t_stop - t_start) << " ms" << std::endl;

结果输出:

Insert static 1000 cost time 5322 ms

二、使用事务提升插入效率

使用 BEGIN 命令手动启动事务,COMMIT 命令是用于把事务调用的更改保存到数据库中的事务命令。由此可以得出,只有等到 COMMIT 命令才会执行磁盘IO的读写,事务中执行的多次插入语句,只用打开关闭一次数据库文件,极大的提升了批量插入数据的效率。

插入 100000 条数据测试:

const static char * insert_record_static = "INSERT INTO tbl_test (a, b, c) VALUES (1, 1, 1);";
sqlite3_exec(db, "begin;", 0, 0, 0);
t_start = clock();
for(int i = 0; i < 100000; i++)
{
    sqlite3_exec(db, insert_record_static, 0, 0, &err);
}
sqlite3_exec(db, "commit;", 0, 0, 0);
t_stop = clock();
std::cout << "Insert static 100000 cost time " << (t_stop - t_start) << " ms" << std::endl;

 结果输出:

Insert static 1000 cost time 1588 ms

三、使用预编译执行提升插入效率

To execute an SQL statement, it must first be compiled into a byte-

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值