当前位置: 移动技术网 > IT编程>开发语言>c# > C# SQLite执行效率的优化教程

C# SQLite执行效率的优化教程

2019年07月18日  | 移动技术网IT编程  | 我要评论

关于sqlite

sqlite是一款轻型的嵌入式的遵守acid的关系型数据库管理系统,诞生已有15个年头了。随着移动互联的发展,现在得到了更广泛的使用。

在使用sqlite之前,我们势必要先了解它一些“个性”的地方。下面是它的一些特点:

1、 自包含。sqlite很大层度上是独立的,他只需要非常小的外部库支持。任何程序能够访问磁盘就可以使用sqlite数据库。这使它适用于嵌入式设备,缺乏桌面计算机支持的基础设施。这也使得sqlite适用于不作任何修改就可运行在不同配置电脑上的程序。

2、 无服务器。大多数sql数据库引擎被实现为一个单独的服务器进程。程序要访问数据库与服务器通信使用某种形式的进程间通信(通常是tcp / ip),向服务器发送请求并接收返回结果。sqlite则不是这种工作方式。对于sqlite,想要访问数据库直接从磁盘上的对数据库文件执行读和写操作。没有中间的服务器进程。

3、 零配置。使用sqlite不需要“安装”。没有“设置”程序。没有服务器进程需要启动,停止,或配置。不需要管理员来创建一个新的数据库实例或访问权限分配给用户。sqlite不使用配置文件。

4、 支持事务。事务数据库的所有更改和查询表现出原子性、一致性、隔离性、持久性(acid)。执行sqlite的事务操作时,要么完全执行,要么不执行,即使写入磁盘的操作被程序崩溃,断电等故障打断。

5、 开源。和前面的特点相比,这个似乎没有多大关系。之所以把它作为一个特点,是因为开源在很大层度上会成为我们选择一个解决方案的重要维度。

本文主要介绍的是关于c# sqlite执行效率优化的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧

一、如要使用sqlite,可以从visual studio中的“程序包管理器控制台”输入以下命令完成安装:

pm> install-package system.data.sqlite.core

sqlite则会安装到项目中,支持32位或64位,如下图所示:

二、新建一个sqlite数据库,名称命名为test.db,其表名称及列定义如下:

三、新建一个控制台应用的解决方案,并输入以下代码,看看sqlite的执行时间:

using system;
using system.collections.generic;
using system.data;
using system.data.sqlite;
using system.diagnostics;

namespace consoleapp
{
 class program
 {
 static void main(string[] args)
 {
  sqliteconnection connection = run(() => new sqliteconnection("data source = test.db"), "连接对象初始化");
  run(() => connection.open(), "打开连接");
  sqlitecommand command = run(() => new sqlitecommand(connection), "命令对象初始化");
  run(() =>
  {
  command.commandtext = $"delete from info;vacuum;update sqlite_sequence set seq ='0' where name ='info';";
  command.executenonquery();
  }, "执行delete命令及收缩数据库");
  run(() =>
  {
  for (int i = 0; i < 3000; i++)
  {
   command.commandtext = $"insert into info(name, age) values ('a{i:000}','{i}')";
   command.executenonquery();
  }
  command.executescalar();
  }, "[---使用事务---]事务执行insert命令");
  list<test> list1 = run(() =>
  {
  command.commandtext = $"select * from info";
  list<test> tests = new list<test>();
  sqlitedatareader reader = command.executereader();
  while (reader.read())
  {
   test t = new test
   {
   id = (long)reader[0],
   name = (string)reader[1],
   age = (long)reader[2]
   };
   tests.add(t);
  }
  reader.close();
  return tests;
  }, "[---不使用事务---]使用executereader方式执行select命令");
  datatable table1 = run(() =>
  {
  command.commandtext = $"select * from info";
  sqlitedataadapter adapter = new sqlitedataadapter(command);
  datatable _table = new datatable();
  adapter.fill(_table);
  return _table;
  }, "[---不使用事务---]使用fill table方式执行select命令");

  run(() =>
  {
  command.commandtext = $"delete from info;vacuum;update sqlite_sequence set seq ='0' where name ='info';";
  command.executenonquery();
  }, "执行delete命令及收缩数据库");
  sqlitetransaction transaction = run(() => connection.begintransaction(), "开始事务");
  run(() => 
  {
  for (int i = 0; i < 3000; i++)
  {
   command.commandtext = $"insert into info(name, age) values ('a{i:000}','{i}')";
   command.executenonquery();
  }
  var result = command.executescalar();
  }, "[---使用事务---]执行insert命令");
  list<test> list2 = run(() =>
  {
  command.commandtext = $"select * from info";
  list<test> tests = new list<test>();
  sqlitedatareader reader = command.executereader();
  while (reader.read())
  {
   test t = new test
   {
   id = (long)reader[0],
   name = (string)reader[1],
   age = (long)reader[2]
   };
   tests.add(t);
  }
  reader.close();
  return tests;
  }, "[---使用事务---]使用executereader方式执行select命令");
  datatable table2 = run(() =>
  {
  command.commandtext = $"select * from info";
  sqlitedataadapter adapter = new sqlitedataadapter(command);
  datatable _table = new datatable();
  adapter.fill(_table);
  return _table;
  }, "[---使用事务---]使用fill table方式执行select命令");
  run(() => transaction.commit(), "提交事务");
  run(() => connection.close(), "关闭连接");
  console.readkey();
 }

 public static void run(action action,string description)
 {
  stopwatch sw = stopwatch.startnew();
  action();
  console.writeline($"--> {description}: {sw.elapsedmilliseconds}ms");
 }

 public static t run<t>(func<t> func, string description)
 {
  stopwatch sw = stopwatch.startnew();
  t result = func();
  console.writeline($"--> {description}: {sw.elapsedmilliseconds}ms");
  return result;
 }
 }

 class test
 {
 public long id { set; get; }
 public string name { set; get; }
 public long age { set; get; }
 }
}

程序运行结果如下:

四、根据以上的程序运行结果,可以得出以下结论:

1)sqliteconnection对象初始化、打开及关闭,其花费时间约为109ms,因此,最好不要频繁地将该对象初始化、打开与关闭,这与sql server不一样,在这里建议使用单例模式来初始化sqliteconnection对象;

在网上查找了sqlitehelper帮助类,但很多都是没执行一次sql语句,都是使用这样的流程:初始化连接对象->打开连接对象->执行命令->关闭连接对象,如下的代码所示:

public int executenonquery(string sql, params sqliteparameter[] parameters) 
 { 
  int affectedrows = 0; 
  using (sqliteconnection connection = new sqliteconnection(connectionstring)) 
  { 
  using (sqlitecommand command = new sqlitecommand(connection)) 
  { 
   try 
   { 
   connection.open(); 
   command.commandtext = sql; 
   if (parameters.length != 0) 
   { 
    command.parameters.addrange(parameters); 
   } 
   affectedrows = command.executenonquery(); 
   } 
   catch (exception) { throw; } 
  } 
  } 
  return affectedrows; 
 }

根据以上的结论,如果要求执行时间比较快的话,这样的编写代码方式实在行不通。

2)使用executereader方式比使用adapter fill table方式快一点点,但这不是绝对的,这取决于编写的代码;

3)无论是执行插入或查询操作,使用事务比不使用事务快,尤其是在批量插入操作时,减少得时间非常明显;

比如在不使用事务的情况下插入3000条记录,执行所花费的时间为17.252s,而使用事务,执行时间只用了0.057s,效果非常明显,而sql server不存在这样的问题。

4)不能每次执行一条sql语句前开始事务并在sql语句执行之后提交事务,这样的执行效率同样是很慢,最好的情况下,是在开始事务后批量执行sql语句,再提交事务,这样的效率是最高的。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网