确保所有更新都成功完成?

时间:2013-03-20 19:39:38

标签: c# asp.net .net sql-server sql-server-2008

我有一些存储过程可以在提交新表单时对各个表进行各种更新和插入。它们都来自我拥有的C#应用​​程序。

现在所有内容都是try catch格式,有没有办法可以确保在将更改提交到数据库之前已经成功完成了所有内容?

所以让我们说前三个存储过程的所有内容都已经完成,但是第四个存储过程失败了,我想要反转前三个已经完成的操作。

全部或全部类型的交易。

4 个答案:

答案 0 :(得分:2)

我不确定你是如何配置它的;但你显然可以使用SqlException类。但另一种方法可能是:

int result = command.ExecuteNonQuery();
if(result == 1)
{
    // Successfully Entered A Row
}
else
{
    // Insert Row Failed
}

这是一种可能的测试方法。本质上它是测试查询,如果它带回一行然后它成功,如果不成功,它将失败。我不确定它是否符合您的标准,但这是您可以测试的两种方式。


<强>更新

因为我无法阅读 - 但我相信你想要实现一种Transactioning形式。这将实际处理所有请求,如果失败,它将回滚更改。它确实增加了很多开销,在某些情况下可能会导致其他性能问题。因此,您需要根据自己的需要定制和优化数据库吞吐量。

以下是一些信息from MSDN on it

希望这有帮助。

答案 1 :(得分:2)

您需要使用TransactionScope类(System.Transactions.TransactionScope)

//assuming Table1 has a single INT column, Column1 and has one row with value 12345
//and connectionstring contains a valid connection string to the database.
    //this automatically starts a transaction for you
try
{
            using (TransactionScope ts = new TransactionScope())
            {
        //you can open as many connections as you like within the scope although they need to be on the same server. And the transaction scope goes out of scope if control leaves this code.
               using (SqlConnection conn = new SqlConnection(connectionstring))
               {
                  conn.Open();
                  using (SqlCommand comm = new SqlCommand("Insert into Table1(Column1) values(999)")
                  {
                    comm.ExecuteNonQuery();
                  }
                   using (SqlCommand comm1 = new SqlCommand("DELETE from Table1 where Column1=12345"))
                   {
                     comm1.ExecuteNonQuery();
                   }
                }//end using conn
               ts.Complete() ; //commit the transaction; Table1 now has 2 rows (12345 and 999) 
            }//end using ts

}
  catch(Exception ex)
   {
     //Transaction is automatically rolled back for you at this point, Table1 retains original row.
   }

答案 2 :(得分:0)

我会捕获您在前3个中添加的新项目的唯一键,如果您遇到失败,只需根据这些键删除。

答案 3 :(得分:0)