Sqlite   发布时间:2022-05-22  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了SQLite批量插入优化方法大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
sqlite的数据库本质上来讲就是一个磁盘上的文件,所以一切的数据库操作其实都会转化为对文件的操作,而频繁的文件操作将会是一个很好时的过程,会极大地影响数据库存取的速度。
例如:向数据库中插入100万条数据,在默认的情况下如果仅仅是执行
sqlite3_exec(db,“insert into name values ‘lxkxf',‘24'; ”,&zErrMsg);
将会重复的打开关闭数据库文件100万次,所以速度当然会很慢。因此对于这种情况我们应该使用“事务”。
具体方法如下:在执行sql语句之前和sql语句执行完毕之后加上
rc = sqlite3_exec(db,"BEGIN;",&zErrMsg);
//执行sql语句
rc = sqlite3_exec(db,"COMMIT;",&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,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

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

androID中的方法,

解决方法:

添加事务处理,把5000条插入作为一个事务

dataBase.begintransaction();//手动设置开始事务

//数据插入操作循环

dataBase.settransactionsuccessful();//设置事务处理成功,不设置会自动回滚不提交

dataBase.endtransaction();//处理完成




@H_262_78@PS,在AndroiD中一般是使用 ContentResolver来包装下sqlite,自带一个批量插入的方法

public final intbulkInsert(Uriurl,ContentValues[]values)

Since: API Level 1

Inserts multiple rows into a table at the given URl. This function make no guarantees about the atomicity of the insertions.

Parameters
@H_489_102@ url The URL of the table to insert into. values The initial values for the newly inserted rows. The key is the column name for the fIEld. Passing null will create an empty row.
Returns

大佬总结

以上是大佬教程为你收集整理的SQLite批量插入优化方法全部内容,希望文章能够帮你解决SQLite批量插入优化方法所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: