C# - 如何在SQL Server中实现begin trans,commit trans和rollback

时间:2017-02-15 06:00:35

标签: c# sql-server

我想在我的代码中插入一个函数,即begin,commit和rollback trans,因为数据容易出错。我的代码是这样的:

clsDBConnect dbConn = new clsDBConnect();
SqlCommand CMD;
SqlDataReader Reader;

private void Save()
{
     CMD = new SqlCommand("SELECT * FROM tblEmployees", dbConn.connection);

     Reader = CMD.ExecuteReader();

     while (Reader.Reader())
     {
          while(variable1 != variable2)
          {
               //Lots of CMD.ExecuteNonQuery();
               //Lots of Reader
               //Lots of computation
               variable1 += 1;
          }
     }
}

如何在循环期间发生错误时回滚插入和更新

谢谢!

1 个答案:

答案 0 :(得分:0)

事务处理以这样的方式完成:

DbTransaction trans = dbConn.BeginTransaction();
try
{
    // ... do your stuff...

    // Last line of the try-block... if you are still alive here, commit
    trans.Commit();
}
catch (Exception e)
{
     // Something evil happened... Rollback
     trans.Rollback();
}