2016-01-12 259 views
0

我正在使用OleDbDataAdapter類從Access(.mdb)文件中獲取數據。OleDbDataAdapter填充方法性能不佳

OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Environment.CurrentDirectory+"\\Data.mdb;Jet OLEDB:Database Password=pass"); 
     OleDbCommand com = new OleDbCommand(query, con); 
     DataTable dt = new DataTable(); 
     con.Open(); 
     OleDbDataAdapter oda = new OleDbDataAdapter(com); 
     oda.Fill(dt); 
     oda.Dispose(); 
     com.Parameters.Clear(); 
     con.Close(); 
     return dt; 

問題是,通過調試我發現,oda.Fill(dt)需要很長時間才能執行。 (大約10秒)

我在數據庫中有50,000條記錄,我只需要檢索1行。

請幫忙。先謝謝你。

+1

你的「查詢」是什麼?你的桌子有索引或什麼的? –

+0

如果您使用'DataReader',則只能讀取第一行,而不必處理其他不需要的記錄。 – Hambone

+0

這是我的查詢:'select_mname,received_date,measure_date,height,weight,calory,pbf_rate,std_weight,member_data where id_number = 1000' –

回答

2

如果你需要的是一排嘗試使用數據讀取器,如下圖所示,你,你將需要調整片如數據庫名,字段列表等

注意我寫輸出到IDE輸出窗口,在使用代碼/數據進行嘗試時打開它。

public partial class Form1 : Form 
{ 
    private void button1_Click(object sender, EventArgs e) 
    { 
     int id = 0; 
     if (int.TryParse(textBox1.Text, out id)) 
     { 
      OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder(); 
      Builder.Provider = "Microsoft.Jet.OLEDB.4.0"; 
      Builder.DataSource = Path.Combine(Application.StartupPath, "Database1.mdb"); 

      using (OleDbConnection cn = new OleDbConnection(Builder.ConnectionString)) 
      { 
       string selectStatement = "SELECT UserName, JoinMonth FROM Users WHERE Identifier = @Identifier"; 
       using (OleDbCommand cmd = new OleDbCommand { CommandText = selectStatement, Connection = cn }) 
       { 
        cmd.Parameters.Add(new OleDbParameter { ParameterName = "@Identifier", DbType = DbType.Int32, Value = id }); 
        cn.Open(); 
        OleDbDataReader dr = cmd.ExecuteReader(); 
        if (dr.HasRows) 
        { 
         dr.Read(); 
         Console.WriteLine("{0} - {1}", dr.GetString(0), dr.GetString(1)); 
        } 
        else 
        { 
         Console.WriteLine("Not located"); 
        } 
       } 
      } 
     } 
    } 
} 
+0

非常感謝你的工作。 –

+0

很高興爲你工作:-) –