SQLite事务<转载>

SQLite事务优化
本文通过对比测试,展示了在SQLite中使用事务进行批量数据插入时的显著性能提升。通过简单的代码修改,将每次插入都开启事务的方式改为一次事务内完成所有插入,使得1000条记录的插入时间从2分钟缩短到了0.2秒。

耗时 2 分钟!
下面是测试代码。using System.Data;
using System.Data.Common;
using System.Data.SQLite;

// 创建数据库文件
File.Delete("test1.db3");
SQLiteConnection.CreateFile("test1.db3");

DbProviderFactory factory = SQLiteFactory.Instance;
using (DbConnection conn = factory.CreateConnection())
{
  // 连接数据库
  conn.ConnectionString = "Data Source=test1.db3";
  conn.Open();

  // 创建数据表
  string sql = "create table [test1] ([id] INTEGER PRIMARY KEY, [s] TEXT COLLATE NOCASE)";
  DbCommand cmd = conn.CreateCommand();
  cmd.Connection = conn;
  cmd.CommandText = sql;
  cmd.ExecuteNonQuery();

  // 添加参数
  cmd.Parameters.Add(cmd.CreateParameter());
 
  // 开始计时
  Stopwatch watch = new Stopwatch();
  watch.Start();
 
  // 连续插入1000条记录
  for (int i = 0; i < 1000; i++)
  {
    cmd.CommandText = "insert into [test1] ([s]) values (?)";
    cmd.Parameters[0].Value = i.ToString();

    cmd.ExecuteNonQuery();
  }

  // 停止计时
  watch.Stop();
  Console.WriteLine(watch.Elapsed);
}

哎~~~~ 一个常识性的错误,加几行代码 (新增代码标记 "// <-------------------")。

using System.Data;
using System.Data.Common;
using System.Data.SQLite;

// 创建数据库文件
File.Delete("test1.db3");
SQLiteConnection.CreateFile("test1.db3");

DbProviderFactory factory = SQLiteFactory.Instance;
using (DbConnection conn = factory.CreateConnection())
{
  // 连接数据库
  conn.ConnectionString = "Data Source=test1.db3";
  conn.Open();

  // 创建数据表
  string sql = "create table [test1] ([id] INTEGER PRIMARY KEY, [s] TEXT COLLATE NOCASE)";
  DbCommand cmd = conn.CreateCommand();
  cmd.Connection = conn;
  cmd.CommandText = sql;
  cmd.ExecuteNonQuery();

  // 添加参数
  cmd.Parameters.Add(cmd.CreateParameter());
 
  // 开始计时
  Stopwatch watch = new Stopwatch();
  watch.Start();
 
  DbTransaction trans = conn.BeginTransaction(); // <-------------------
  try
  {
    // 连续插入1000条记录
    for (int i = 0; i < 1000; i++)
    {
      cmd.CommandText = "insert into [test1] ([s]) values (?)";
      cmd.Parameters[0].Value = i.ToString();

      cmd.ExecuteNonQuery();
    }

    trans.Commit(); // <-------------------
  }
  catch
  {
    trans.Rollback(); // <-------------------
    throw; // <-------------------
  }

  // 停止计时
  watch.Stop();
  Console.WriteLine(watch.Elapsed);
}

执行一下,耗时 0.2 秒。这差距是不是太大了点? 

为什么只是简单启用了一个事务会有这么大的差距呢?很简单,SQLite 缺省为每个操作启动一个事务,那么原代码 1000 次插入起码开启了 1000 个事务,"事务开启 + SQL 执行 + 事务关闭" 自然耗费了大量的时间,这也是后面显示启动事务后为什么如此快的原因。其实这是数据库操作的基本常识,大家要紧记,不好的代码效率差的不是一点半点。

CAPI3REF: Online Backup API. ** ** The backup API copies the content of one database into another. ** It is useful either for creating backups of databases or ** for copying in-memory databases to or from persistent files. ** ** See Also: [Using the SQLite Online Backup API] ** ** ^SQLite holds a write transaction open on the destination database file ** for the duration of the backup operation. ** ^The source database is read-locked only while it is being read; ** it is not locked continuously for the entire backup operation. ** ^Thus, the backup may be performed on a live source database without ** preventing other database connections from ** reading or writing to the source database while the backup is underway. ** ** ^(To perform a backup operation: ** <ol> ** <li><b>sqlite3_backup_init()</b> is called once to initialize the ** backup, ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer ** the data between the two databases, and finally ** <li><b>sqlite3_backup_finish()</b> is called to release all resources ** associated with the backup operation. ** </ol>)^ ** There should be exactly one call to sqlite3_backup_finish() for each ** successful call to sqlite3_backup_init(). ** ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b> ** ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the ** [database connection] associated with the destination database ** and the database name, respectively. ** ^The database name is "main" for the main database, "temp" for the ** temporary database, or the name specified after the AS keyword in ** an [ATTACH] statement for an attached database. ** ^The S and M arguments passed to ** sqlite3_backup_init(D,N,S,M) identify the [database connection] ** and database name of the source database, respectively. ** ^The source and destination [database connections] (parameters S and D) ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with ** an error. **翻译
最新发布
09-23
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值