SQLite最佳化方法

來源:互聯網
上載者:User

例如:向資料庫中插入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




可見使用了事務之後卻是極大的提高了資料庫的效率。但是我們也要注意,使用事務也是有一定的開銷的,所以對於資料量很小的操作可以不必使用,以免造成而外的消耗。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.