2013-06-24 60 views
-1

我將使用C#實現Window應用程序的數據庫訪問層。數據庫(.accdb)位於項目文件中。當涉及通過交換機連接到一個訪問數據庫的兩個筆記本(客戶端)時,它會引發DBConcurrency異常錯誤。我的目標是檢查sql執行的時間戳,然後運行sql。 您能否爲我提供一些指導方針來實現這一目標?插入或更新時訪問數據庫事務

下面是我的代碼

 protected void btnTransaction_Click(object sender, EventArgs e) 
    { 
     string custID = txtID.Text; 
     string CompName = txtCompany.Text; 
     string contact = txtContact.Text; 
     string city = txtCity.Text; 


     string connString = ConfigurationManager.ConnectionStrings["CustomersDatabase"].ConnectionString; 
     OleDbConnection connection = new OleDbConnection(connString); 
     connection.Open(); 
     OleDbCommand command = new OleDbCommand(); 
     command.Connection = connection; 
     OleDbTransaction transaction = connection.BeginTransaction(); 
     command.Transaction = transaction; 

     try 
     { 
      command.CommandText = "INSERT INTO Customers(CustomerID, CompanyName, ContactName, City, Country) VALUES(@CustomerID, @CompanyName, @ContactName, @City, @Country)"; 
      command.CommandType = CommandType.Text; 
      command.Parameters.AddWithValue("@CustomerID", custID); 
      command.Parameters.AddWithValue("@CompanyName", CompName); 
      command.Parameters.AddWithValue("@ContactName", contact); 
      command.Parameters.AddWithValue("@City", city); 

      command.ExecuteNonQuery(); 

      command.CommandText = "UPDATE Customers SET ContactName = @ContactName2 WHERE CustomerID = @CustomerID2"; 
      command.CommandType = CommandType.Text; 
      command.Parameters.AddWithValue("@CustomerID2", custIDUpdate); 
      command.Parameters.AddWithValue("@ContactName2", contactUpdate); 
      command.ExecuteNonQuery(); 

      adapter.Fill(table); 
      GridView1.DataSource = table; 
      GridView1.DataBind(); 

      transaction.Commit(); 
      lblMessage.Text = "Transaction successfully completed"; 
     } 
     catch (Exception ex) 
     { 
      transaction.Rollback(); 
      lblMessage.Text = "Transaction is not completed"; 
     } 
     finally 
     { 
      connection.Close(); 
     } 

} 

回答

1

我注意到兩件事:

  1. 您的插入CommandText中已經指定@Country參數,但你沒有相應的參數添加到.Parameters集合。

  2. 您嘗試重新使用command對象爲您更新通過更改的CommandText和增加更多的參數,但你不會從你的INSERT所以大概擺脫之前的參數的他們仍然在地方,這肯定會混淆UPDATE命令。

  3. 您以錯誤的順序指定UPDATE參數。 ACE.OLEDB 忽略參數名稱,所以必須將參數添加到確切的集合中的.Parameters集合中,以使它們出現在CommandText中。

我也困惑,:

  • 你爲什麼不試圖綁定在GridView之前提交事務

  • 爲什麼你需要一個交易畢竟,INSERT和UPDATE看起來是不相關的。