回滚SQL Server查询

Lor*_*lix 1 c# sql-server asp.net

我找到了一些关于回滚SQL Server查询的链接,但是在实现它时遇到了问题.由于我插入和更新的信息需要始终正确,我需要确保这是事先工作.现在,我已经有了一个try/catch块,我知道回滚会进入catch块.例如,这是我的代码:

using (SqlConnection conn5 = new SqlConnection(connString)) 
{
    try 
    {
        string query = "INSERT QUERY";
        SqlCommand cmd = new SqlCommand(query, conn5);
        // PARAMETERS

        conn5.open();
        cmd.ExecuteNonQuery();
    }
    catch 
    { 
        cmd.Rollback();
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过cmd.RollBack()但它只是在我的脸上吹了.

And*_*bel 5

您打开一个事务范围.除非Complete()调用该方法,否则它将自动执行回滚.

using (var tScope = new TransactionScope())
using (SqlConnection conn5 = new SqlConnection(connString)) 
{
  string query = "INSERT QUERY";
  SqlCommand cmd = new SqlCommand(query, conn5);
  PARAMETERS

  conn5.open();
  cmd.ExecuteNonQuery();

  // If an exception is thrown, the call to Complete() will never be reached and the
  // changes will be rolled back.
  tScope.Complete();
}
Run Code Online (Sandbox Code Playgroud)

  • TransactionScope就是答案,但不是这样的.强制阅读[使用新的TransactionScope()认为有害](http://blogs.msdn.com/b/dbrowne/archive/2010/06/03/using-new-transactionscope-considered-harmful.aspx?Redirected=true) (2认同)