例如:向數(shù)據(jù)庫(kù)中插入100萬(wàn)條數(shù)據(jù),在默認(rèn)的情況下如果僅僅是執(zhí)行
sqlite3_exec(db, “insert into name values ‘lxkxf', ‘24'; ”, 0, 0, &zErrMsg);
將會(huì)重復(fù)的打開(kāi)關(guān)閉數(shù)據(jù)庫(kù)文件100萬(wàn)次,所以速度當(dāng)然會(huì)很慢。因此對(duì)于這種情況我們應(yīng)該使用“事務(wù)”。
具體方法如下:在執(zhí)行SQL語(yǔ)句之前和SQL語(yǔ)句執(zhí)行完畢之后加上
rc = sqlite3_exec(db, "BEGIN;", 0, 0, &zErrMsg);
//執(zhí)行SQL語(yǔ)句
rc = sqlite3_exec(db, "COMMIT;", 0, 0, &zErrMsg);
這樣SQLite將把全部要執(zhí)行的SQL語(yǔ)句先緩存在內(nèi)存當(dāng)中,然后等到COMMIT的時(shí)候一次性的寫入數(shù)據(jù)庫(kù),這樣數(shù)據(jù)庫(kù)文件只被打開(kāi)關(guān)閉了一次,效率自然大大的提高。有一組數(shù)據(jù)對(duì)比:
測(cè)試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
測(cè)試2: 使用事務(wù) 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
可見(jiàn)使用了事務(wù)之后卻是極大的提高了數(shù)據(jù)庫(kù)的效率。但是我們也要注意,使用事務(wù)也是有一定的開(kāi)銷的,所以對(duì)于數(shù)據(jù)量很小的操作可以不必使用,以免造成而外的消耗。