C# SQLite 读取器在循环缓慢

本文关键字:循环 缓慢 SQLite 读取 | 更新日期: 2023-09-27 18:19:21

我正在使用数据读取器从sqlite数据库中检索数据。这是在双 for 循环中执行的。但它非常慢,因为现在它正在多次执行 sql 查询。

有没有更快速的方法可以做到这一点?以下是我现在正在做的事情的简短版本:

for(int i=0;i < horizontal; i++)
{
  for(int j=0;j < vertical; j++)
  {
    SQLiteConnection con = new SQLiteConnection(dbConnection);
    con.Open();
    SQLiteCommand cmd = new SQLiteCommand(con);
    cmd.CommandText = query;        
    SQLiteDataReader reader = cmd.ExecuteReader();
    dt.Load(reader);
    con.Close();
    // Perform some actions onto DataTable data
  }
}

编辑:在循环之前打开和关闭并没有多大帮助。我正在尝试查询位置列在 4 点之间的表格的所有行,对其执行一些计算并移动到下一个单元格(想想网格(。

C# SQLite 读取器在循环缓慢

SQLiteConnection con = new SQLiteConnection(dbConnection);
con.Open();
SQLiteCommand cmd = new SQLiteCommand(con);
for(int i=0;i < horizontal; i++)
{
  for(int j=0;j < vertical; j++)
  {
    cmd.CommandText = query;    
    SQLiteDataReader reader = cmd.ExecuteReader();
    dt.Load(reader);
    // Perform some actions onto DataTable data
  }
}
con.Close();

只需更改命令文本,无需每次都实例化一个新的。此外,仅在完成查询后关闭它。

如果您使用相同的连接,则可以创建 SQLiteConnection 对象并在迭代上方打开连接,您还应该关闭迭代下的连接。它应该更快。

using Finisar.SQLite;吗?

如果是这样,请尝试更改为 using System.Data.SQLite; 。这对我非常有帮助,表格 6s 减少到 150 毫秒。