2012-11-21 44 views
0

我正在使用OLEDB查詢使用日期時間選擇器的Excel文件,但我不斷收到Cireria表達式錯誤中的數據類型不匹配。查詢字符串數據類型不匹配

的日期在Excel中的格式是「2012年6月8日10:00」

 DateTime time = dateTimePicker1.Value;    

     MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time + "')", MyConnection); 



     DtSet = new System.Data.DataSet(); 
     MyCommand.Fill(DtSet); 


     bindingSource1 = new BindingSource(); 
     bindingSource1.DataSource = DtSet; 
     bindingSource1.DataMember = DtSet.Tables[0].TableName; 
     dataGridView1.DataSource = bindingSource1; 

     MyConnection.Close(); 

回答

1

你逝去的時候查詢作爲一個字符串,所以你能的ToString()到使其工作:

MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time.ToString("%M/dd/yyyy HH:mm") + "')", MyConnection); 

但你真的應該使它成爲一個參數。另外,這樣更安全。

using (OleDbConnection connection = new OleDbConnection(yourConnectionString)) 
    { 
     OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [CR$] where [Req Start Date] >= ?", connection); 
     adapter.SelectCommand.Parameters.Add("@p1", OleDbType.Date); 
     adapter.SelectCommand.Parameters["@p1"].Value = time; 

     try 
     { 
      connection.Open(); 
      adapter.Fill(DtSet); 
     } 
     catch (Exception ex) 
     { 
      //handle error 
     } 
    } 

瞭解更多:OleDbParameter Class

+0

我得到一個錯誤說國有企業不是DATETIME contatin defiitino和使用日期給出了一個錯誤,說沒有找到一個或多個必需參數 – stefan

+0

給定值改變我聲明一點。我看到在添加參數的同時添加值時出現了一些問題。我無法測試這個,所以你可能只是想玩它。 – MikeSmithDev

0

創建一個OleDbCommand,並作爲參數傳遞值。然後使用命令作爲OleDbAdapter構造函數的參數...

string queryString = "select * from [CR$] where ([Req Start Date] >= ?)"; 
OleDbCommand command = new OleDbCommand(queryString, connection); 
command.Parameters.Add("@p1", OleDbType.DateTime).Value = time; 
MyCommand = new OleDbDataAdapter(queryString, MyConnection); 
+0

我收到一個錯誤,表示不會爲DateTIme提供defiitino,並且使用日期會給出錯誤,表示沒有給出一個或多個所需參數的值。 – stefan