資料來源: http://www.cnblogs.com/likebeta/archive/2012/06/15/2551466.html
http://jashliao.pixnet.net/blog/post/220572783

 


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";//C#要省略
    for (int i=0;i<100;i++)
    {
        strSql+="insert into fuck values(null,'heh');\n";//重點就是把所有語法寫在一起,一次送
    }
    strSql+="commit;";//C#要省略
    //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;

arrow
arrow

    痞客興 發表在 痞客邦 留言(0) 人氣()