c# – SQL Server CE性能,从表中选择需要8s为7000条记录

我有SQL Server CE 3.5数据库.我运行以下代码:

private void Load(string sql)
{
  if (connection.State != ConnectionState.Open)
    connection.Open();
  SqlCeDataAdapter sqlCeDataAdapter = new SqlCeDataAdapter(sql, connection);

  Stopwatch watch = new Stopwatch();

  DataSet dataSet = new DataSet();
  try
  {
    Cursor.Current = Cursors.WaitCursor;
    watch.Start();

    sqlCeDataAdapter.Fill(dataSet, "items");
    sqlCeDataAdapter.Dispose();

    var myBind = new BindingSource(dataSet, "items");
    grid.DataSource = myBind;
  }
  finally
  {
    watch.Stop();
    Cursor.Current = Cursors.Default;
    MessageBox.Show(watch.ElapsedMilliseconds.ToString());
  }      
}

Load ("select a1, a2 from table");

SQL Server CE是否很长,还是应该加载更快?

我该怎么做才能让这个选择更快?

当我使用其他表的连接时,时间急剧增长……

编辑:

我已经更改了以下新版本的代码,但仍然是7.5秒. …

private void Load2 (string sql)
{
  if (connection.State != System.Data.ConnectionState.Open)
  {
    connection.Open();
  }

  using (SqlCeCommand command = new SqlCeCommand(sql, connection))
  {
    Stopwatch watch = new Stopwatch();

    Cursor.Current = Cursors.WaitCursor;
    watch.Start();
    using (SqlCeDataReader reader = command.ExecuteReader())
    {
      DataSet dataSet = new DataSet();

      dataSet.Tables.Add("items");

      dataSet.Tables["items"].Columns.Add("s1");
      dataSet.Tables["items"].Columns.Add("s2");

      while (reader.Read())
      {
        string s1 = reader.GetString(0);
        string s2 = reader.GetString(1);

        dataSet.Tables["items"].Rows.Add(s1, s2);
      }
      watch.Stop();
      Cursor.Current = Cursors.Default;
      MessageBox.Show(watch.ElapsedMilliseconds.ToString());

      BindingSource binding = new BindingSource(dataSet, "items");
      grid.DataSource = binding;
    }
  }
}

最佳答案 SqlCeDataAdapter.Fill(…)只是出了名的慢.如果您真的需要性能,则需要使用
SqlCeDataReader.

private void Load(string sql) {
    if (connection.State != System.Data.ConnectionState.Open) {
        connection.Open();
    }

    using (SqlCeCommand command = new SqlCeCommand(sql, connection)) {
        using (SqlCeDataReader reader = command.ExecuteReader()) {
            DataSet dataSet = new DataSet();

            dataSet.Tables.Add("items");

            while (reader.Read()) {
                DataRow row = dataSet.Tables["items"].NewRow();
                // fill your row

                dataSet.Tables["items"].Rows.Add(row);
            }

            BindingSource binding = new BindingSource(dataSet, "items");
            grid.DataSource = binding;
        }
    }
}

当然,添加正确的错误处理,并根据自己的喜好进行清理.与DbDataAdapter实现相比,还有Entity Framework在性能上相当不错.

因为您使用的是SqlCe,所以您还有其他限制因素,例如磁盘IO,并且您没有服务器处理任何类型的优化的SQL事务.

点赞