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

2020-01-05 09:34:23于海丽

程序运行结果如下:

C#,SQLite,执行效率

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

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