I have following code that does work of inserting data in Sqlite Database but it is too slow. Sqlite FAQ says that it can support of 50K insertion at a time. I have attached the following code.
SqliteBuffer.h
#ifndef SQLITE_BUFFER_H #define SQLITE_BUFFER_H #include "sqlite3.h" #include <iostream> class SqliteBuffer { std::string db_name_; sqlite3 *db_; sqlite3_stmt *insert_stmt_; bool has_transaction_begun; public: SqliteBuffer(std::string db_name); ~SqliteBuffer(); int CreateTable(); void SaveMessage(std::string msg); void BeginTransaction(); void EndTransaction(); }; #endif SqliteBuffer.cc
#include "SqliteBuffer.h" int SqliteBuffer::CreateTable() { sqlite3_stmt *create = NULL; if(sqlite3_prepare_v2(db_,"CREATE TABLE mytable (sif INTEGER PRIMARY KEY, log VARCHAR);",-1,&create,NULL)==SQLITE_OK){ sqlite3_step(create); sqlite3_finalize(create); } return 0; } SqliteBuffer::SqliteBuffer(std::string db_name) { int rc = sqlite3_open_v2(db_name.c_str(), &db_, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL); if(rc!=SQLITE_OK){ sqlite3_close_v2(db_); } CreateTable(); rc = sqlite3_prepare_v2(db_, "INSERT INTO mytable(log) VALUES (@LOG)", -1, &insert_stmt_, NULL); } void SqliteBuffer::SaveMessage(std::string message) { BeginTransaction(); sqlite3_bind_text(insert_stmt_,1,message.c_str(),-1,SQLITE_TRANSIENT); sqlite3_step(insert_stmt_); sqlite3_clear_bindings(insert_stmt_); sqlite3_reset(insert_stmt_); } void SqliteBuffer::BeginTransaction() { if(has_transaction_begun == false){ has_transaction_begun = true; sqlite3_exec(db_, "BEGIN TRANSACTION;",NULL,NULL,NULL); } } void SqliteBuffer::EndTransaction() { if(has_transaction_begun == true){ has_transaction_begun = false; sqlite3_exec(db_, "END TRANSACTION;",NULL,NULL,NULL); } } main.cc
#include "SqliteBuffer.h" int main() { SqliteBuffer *sql = new SqliteBuffer("E:\\asdf.db"); for(int i(0); i<2000; i++){ sql->SaveMessage("HELLO WORLD"); } return 0; } I have tested these code in Visual Studio 10 and they works but the insertion is very slow. Am I missing something here.
has_transaction_begun, the program is undefined.sqlite3_*functions. Due to the error shown by molbdnilo, the lastsqlite3_execwill fail (because there is no active transaction).