-3

I would like to insert a function in my code which is begin,commit, and rollback trans because the data is prone to errors. my code is this:

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;
          }
     }
}

How can I rollback inserts and updates when error occurs during the loop?

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nikko Sunglao
  • 47
  • 2
  • 9

1 Answers1

0

Transaction handling is done in a way like this:

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();
}
Grisgram
  • 3,105
  • 3
  • 25
  • 42