手机
当前位置:查字典教程网 >编程开发 >SQLite >SQLite优化方法
SQLite优化方法
摘要:例如:向数据库中插入100万条数据,在默认的情况下如果仅仅是执行sqlite3_exec(db,“insertintonamevalues‘...

例如:向数据库中插入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

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

【SQLite优化方法】相关文章:

SQLite速度评测代码

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

SQLite学习手册(SQLite在线备份)

SQLite教程(三):数据表和视图简介

SQLite教程(五):数据库和事务

SQLite3 命令行操作指南

SQLite 内存数据库学习手册

Sqlite数据库里插入数据的条数上限是500

SQLite 错误码整理

SQLite中的WAL机制详细介绍

精品推荐
分类导航