SQLite Bulk Insert

One of our projects involved inserting in a SQLite database – however, INSERT is really slow – I could only do few dozen INSERTs per second.


Research led me to this:


“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. ”


Now I had to trawl around to find the commands, see below:


//start code
int fld;
int nRows=0;
CppSQLite3DB db;


try
{
db.open(gszFile);


char buf[1500];


db.execDML("begin transaction;");


for (int r = lbound; r < ubound; r++) {


sprintf(buf, "insert into wavelength (testnumber, lamda, counts) values ('%d', '%f', '%f');", testnumber, wavelengths[r], wavelengtharray[r]);


nRows = db.execDML(buf);

}


db.execDML("commit transaction;");


//end code


I did this using the CPPSQLite library, found at: http://www.codeproject.com/KB/database/CppSQLite.aspx

http://www.codeproject.com/KB/database/CppSQLite.aspx



Live the dream!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>