3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
Sqlite 插入資料(INSERT INTO)加速方法[C/C++/C#都OK] 資料來源: http://www.cnblogs.com/likebeta/archive/2012/06/15/2551466.html sqlite 插入資料很慢的原因:sqlite在沒有顯式使用事務的時候會為每條insert都使用事務操作,而sqlite資料庫是以檔的形式存在磁片中,就相當於每次訪問時都要打開一次檔,如果對資料進行大量的操作,時間都耗費在I/O操作上,所以很慢。 解決方法是顯式使用事務的形式提交:因為我們開始事務後,進行的大量操作的語句都保存在記憶體中,當提交時才全部寫入資料庫,此時,資料庫檔也就只用打開一次。 我在沒有顯式使用事務形式插入100條資料時用了12.226s;用顯式事務形式,插入100條只用了0.172s,插入1000000條也才34.891s,相關很大吧。 顯式使用事務的例子:   #include #include using namespace std; #include “sqlite/sqlite3.h” int main() {     sqlite3* db;     int nResult = sqlite3_open(“test.db”,&db);     if (nResult != SQLITE_OK)     {         cout<         return 0;     }     else     {         cout<     }     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<          sqlite3_free(errmsg);         return 0;     }     string strSql;     strSql+=”begin;\n”;//C#要省略     for (int i=0;i<100;i++)     {         strSql+=”insert into fuck values(null,’heh’);\n”;//重點就是把所有語法寫在一起,一次送     }     strSql+=”commit;”;//C#要省略     //cout<     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<         sqlite3_free(errmsg);         return 0;     }     cout<     cout<     return 0; }         

本文由jashliaoeuwordpress提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦