SQLite 插入大量数据慢的解决方法

2,722 阅读1分钟

  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打开数据库失败:sqlite3_errmsg(db)endl; p=

  return 0;

  }

  else

  {

  cout数据库打开成功endl; p=

  }

  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);

  couterrmsg; p=

  sqlite3_free(errmsg);

  return 0;

  }

  string strSql;

  strSql+=begin;\n;

  for (int i=0;i100;i++)

  {

  strSql+=insert into fuck values(null,'heh');\n;

  }

  strSql+=commit;;

  //coutstrsqlendl; p=

  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);

  couterrmsgendl; p=

  sqlite3_free(errmsg);

  return 0;

  }

  coutstart:tm_s.wminute:tm_s.wsecond:tm_s.wmillisecondsendl; p=

  coutend :tm_e.wminute:tm_e.wsecond:tm_e.wmillisecondsendl; p=

  return 0;