使用事務提升sqlite insert的效能,sqliteinsert
昨天發現sqlite插入效能很低,搜尋了一下發現,其實sqlite的插入可以做到每秒50000條,但是處理事務的速度慢:
(19) INSERT is really slow - I can only do few dozen INSERTs per second
Actually, SQLite will easily do 50,000 or more INSERT statements per second on an average desktop computer. But it will only do a few dozen transactions per second. Transaction speed is limited by the rotational speed of your disk drive. A transaction normally requires two complete rotations of the disk platter, which on a 7200RPM disk drive limits you to about 60 transactions per second.
Transaction speed is limited by disk drive speed because (by default) SQLite actually waits until the data really is safely stored on the disk surface before the transaction is complete. That way, if you suddenly lose power or if your OS crashes, your data is still safe. For details, read about atomic commit in SQLite..
By default, each INSERT statement is its own transaction. But if you surround multiple INSERT statements with BEGIN...COMMIT then all the inserts are grouped into a single transaction. The time needed to commit the transaction is amortized over all the enclosed insert statements and so the time per insert statement is greatly reduced.
sqlite FAQ#19
我原本的代碼沒有使用事務,所以每條insert語句都預設為一個事務。解決的辦法是加上事務,執行SQL的時間就從10秒縮短到了0.07秒
發現了這個以後,我就嘗試把可能的地方都加上事務,但是原本程式有一處邏輯,是執行一大堆insert,如果主鍵衝突就自然無視。但是如果把這堆sql變成事務,就會影響正確資料的插入,所以又把insert語句改成insert or ignore:
insert or ignore into test (id, key) values (20001, 'kyfxbl');
然後再放到一個事務裡,效率大大提升
怎建立SQLite資料庫並Insert資料?
這是因為Sqlite中資料庫是以檔案的形式存在磁碟中,每次訪問時都要開啟一次檔案,如果對資料庫進行大量的操作,速度會很慢。
解決辦法:用事務的形式提交。
因為開始事務後,進行的大量操作的語句都儲存在記憶體中,當提交時才全部寫入資料庫,此時,資料庫檔案也就只用開啟一次。
在進行Insert操作的前後的前後分別添加開啟和關閉事務語句:
rc = sqlite3_exec(db, "begin;", 0,0, &szErrMsg);
for (...)
{
//insert into operate
}
rc = sqlite3_exec(db, "commit;", 0, 0,&szErrMsg);
這樣速度提高了近千倍。
sqlite執行insert語句,返回是SQLITE_OK,但是去看資料庫時找不到新插入的資料
1、執行insert語句的資料庫是否是你查看的資料庫。SqLite資料庫是檔案式資料庫。容易操作資料庫和查看資料庫不一致的問題。
2、使用了事務,Insert之後,沒有提交事務。
3、查看資料庫的時候,是否重新整理資料庫。