sqlite 插入數據很慢的原因:sqlite在沒有顯式使用事務的時候會為每條insert都使用事務操作,而sqlite數據庫是以文件的形式存在磁盤中,就相當於每次訪問時都要打開一次文件,如果對數據進行大量的操作,時間都耗費在I/O操作上,所以很慢。
解決方法是顯式使用事務的形式提交:因為我們開始事務后,進行的大量操作的語句都保存在內存中,當提交時才全部寫入數據庫,此時,數據庫文件也就只用打開一次。
我在沒有顯式使用事務形式插入100條數據時用了12.226s;用顯式事務形式,插入100條只用了0.172s,插入1000000條也才34.891s,相關很大吧。
顯式使用事務的例子:
#include <iostream> #include <windows.h> using namespace std; #include "sqlite/sqlite3.h" int main() { sqlite3* db; int nResult = sqlite3_open("test.db",&db); if (nResult != SQLITE_OK) { cout<<"打開數據庫失敗:"<<sqlite3_errmsg(db)<<endl; return 0; } else { cout<<"數據庫打開成功"<<endl; } char* errmsg; nResult = sqlite3_exec(db,"create table fuck(id integer primary key autoincrement,name varchar(100))",NULL,NULL,&errmsg); if (nResult != SQLITE_OK) { sqlite3_close(db); cout<<errmsg; sqlite3_free(errmsg); return 0; } string strSql; strSql+="begin;\n"; for (int i=0;i<100;i++) { strSql+="insert into fuck values(null,'heh');\n"; } strSql+="commit;"; //cout<<strSql<<endl; SYSTEMTIME tm_s; GetLocalTime(&tm_s); nResult = sqlite3_exec(db,strSql.c_str(),NULL,NULL,&errmsg); SYSTEMTIME tm_e; GetLocalTime(&tm_e); if (nResult != SQLITE_OK) { sqlite3_close(db); cout<<errmsg<<endl; sqlite3_free(errmsg); return 0; } cout<<"start:"<<tm_s.wMinute<<":"<<tm_s.wSecond<<":"<<tm_s.wMilliseconds<<endl; cout<<"end :"<<tm_e.wMinute<<":"<<tm_e.wSecond<<":"<<tm_e.wMilliseconds<<endl; return 0; }
