2014-02-10 96 views
0

我需要使用C#在Access 2000數據庫中插入一條記錄。代碼在SqlConnection失敗。請幫忙。將記錄插入到C#中的Access 2000數據庫中

 string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Trading.mdb"; 
     string commandText = "INSERT INTO Order (OpenDate) VALUES (@OpenDate)"; 

     using (SqlConnection connection = new SqlConnection(connectionString)) 
     { 
      SqlCommand command = new SqlCommand(commandText, connection); 
      command.Parameters.AddWithValue("@OpenDate", DateTime.Now); 

      try 
      { 
       command.Connection.Open(); 
       int response = command.ExecuteNonQuery(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error: {0}" + ex.Message); 
      } 
     }    
+0

它沒有去到代碼的SqlConnection後。 – Nicholas

+0

首先,我想感謝所有發佈他們建議的人。它讓我思考,我已經想出瞭解決方案,雖然讀了很多帖子和反覆試驗這些示例代碼。 – Nicholas

+0

我想問爲什麼我的帖子被擱置。關於這篇文章http://stackoverflow.com/questions/2415703/error-datatype-mismatch-in-c-sharp?爲什麼它不被擱置或任何類型的剋制?爲什麼這裏有雙重標準? – Nicholas

回答

3

問題:您正在使用MS-Access數據庫的工作,但使用SqlServer的對象。

解決方案:你需要使用OleDbConnection對象,而不是SqlConnectionOleDbCommand代替SqlCommand

試試這個:

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Trading.mdb"; 
    string commandText = "INSERT INTO Order (OpenDate) VALUES (?)"; 

    using (OleDbConnection connection = new OleDbConnection(connectionString)) 
    { 
     OleDbCommand command = new OleDbCommand(commandText, connection); 
     command.Parameters.AddWithValue("@OpenDate", DateTime.Now); 

     try 
     { 
      command.Connection.Open(); 
      int response = command.ExecuteNonQuery(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error: {0}" + ex.Message); 
     } 
    }   
相關問題