it编程 > 数据库 > Sqlite

SQLite优化方法

231人参与 2024-05-18 Sqlite

例如:向数据库中插入100万条数据,在默认的情况下如果仅仅是执行

sqlite3_exec(db, “insert into name values ‘lxkxf', ‘24'; ”, 0, 0, &zerrmsg);

将会重复的打开关闭数据库文件100万次,所以速度当然会很慢。因此对于这种情况我们应该使用“事务”。

具体方法如下:在执行sql语句之前和sql语句执行完毕之后加上

rc = sqlite3_exec(db, "begin;", 0, 0, &zerrmsg);

//执行sql语句

rc = sqlite3_exec(db, "commit;", 0, 0, &zerrmsg);



这样sqlite将把全部要执行的sql语句先缓存在内存当中,然后等到commit的时候一次性的写入数据库,这样数据库文件只被打开关闭了一次,效率自然大大的提高。有一组数据对比:



测试1: 1000 inserts

create table t1(a integer, b integer, c varchar(100));
insert into t1 values(1,13153,'thirteen thousand one hundred fifty three');
insert into t1 values(2,75560,'seventy five thousand five hundred sixty');
... 995 lines omitted
insert into t1 values(998,66289,'sixty six thousand two hundred eighty nine');
insert into t1 values(999,24322,'twenty four thousand three hundred twenty two');
insert into t1 values(1000,94142,'ninety four thousand one hundred forty two');

sqlite 2.7.6:
13.061

sqlite 2.7.6 (nosync):
0.223




测试2: 使用事务 25000 inserts

begin;
create table t2(a integer, b integer, c varchar(100));
insert into t2 values(1,59672,'fifty nine thousand six hundred seventy two');
... 24997 lines omitted
insert into t2 values(24999,89569,'eighty nine thousand five hundred sixty nine');
insert into t2 values(25000,94666,'ninety four thousand six hundred sixty six');
commit;

sqlite 2.7.6:
0.914

sqlite 2.7.6 (nosync):
0.757




可见使用了事务之后却是极大的提高了数据库的效率。但是我们也要注意,使用事务也是有一定的开销的,所以对于数据量很小的操作可以不必使用,以免造成而外的消耗。
(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Sqlite 常用函数 推荐

05-18

SQLite速度评测代码

05-18

Sqlite 操作类代码

05-18

保护你的Sqlite数据库(SQLite数据库安全秘籍)

05-18

SQLite数据库管理系统-我所认识的数据库引擎

05-18

sqlite3 top的查询及limit语法介绍

05-18

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论