本文以INSERT為例介紹影響SQLite3速度的方法。
基本方法
SQLite3執(zhí)行INSERT語句的代碼如下:
for (int i=0; i<count; ++i) {
const char *stmt = “INSERT INTO TABLE VALUES(....)”;
sqlite3_exec(db, stmt, 0, 0, 0);
}
開啟事務(wù)
事務(wù)保證數(shù)據(jù)庫執(zhí)行語句的完整性,是開銷較大的動作。每次INSERT語句隱式開啟一個事務(wù),多次INSERT語句則會開啟多次。顯示開啟事務(wù)可以合并多次INSERT語句的事務(wù),如下:
sqlite3_exec(db,"BEGIN;",0,0,0);
for(int i=0; i<count; ++i) {
const char *stmt = “INSERT INTO TABLE VALUES(....)”;
sqlite3_exec(db,ssm.str().c_str(),0,0,0);
}
sqlite3_exec(db,"COMMIT;",0,0,0);
設(shè)置同步
設(shè)置synchronous選項,可選值為full、normal、off,默認(rèn)為full。其值full最安全但最慢,而off最快但數(shù)據(jù)庫存在損壞風(fēng)險。
sqlite3_exec(db,"PRAGMA SYNCHRONOUS = OFF; ",0,0,0);
執(zhí)行準(zhǔn)備
如果執(zhí)行相同的語句,只是數(shù)據(jù)不同,如INSERT不同的數(shù)據(jù)項,可預(yù)先對執(zhí)行語句進(jìn)行預(yù)處理。
sqlite3_stmt *stmt;
const char* sql = "INSERT INTO TABLE VALUES(?,?)";
sqlite3_prepare_v2(db,sql,strlen(sql),&stmt,0);
for(int i=0; i<count; ++i) {
sqlite3_reset(stmt);
sqlite3_bind_int(stmt,1,i);
sqlite3_bind_double(stmt,2,i*i);
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);