1

当提交新表单时,我有一些存储过程可以对几个表进行各种更新和插入。它们都是从我拥有的 C# 应用程序中调用的。

现在一切都是一种try catch格式,有没有一种方法可以确保在实际将更改提交到数据库之前,它们都已成功完成?

因此,假设前 3 个存储过程一切正常,但第 4 个存储过程失败,我想扭转前 3 个存储过程中已经完成的操作。

全有或全无类型的交易。

4

4 回答 4

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.
   }
于 2013-03-20T20:00:16.020 回答
2

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

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

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


更新:

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

这是MSDN 关于它的一些信息。

希望这会有所帮助。

于 2013-03-20T19:46:12.447 回答
0

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

于 2013-03-20T19:46:16.650 回答
0

你应该读这个

wiki:数据库事务

和这个

msdn:编写事务性应用程序

于 2013-03-20T19:47:55.357 回答