search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

Sqlite 插入資料(INSERT INTO)加速方法[C/C++/C#都OK] – jashliao部落格

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 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦