C#中实现事务的实例(精华)

public void RunSqlTransaction(string myConnString)
 {
    SqlConnection myConnection = new SqlConnection(myConnString);
    myConnection.Open();

    SqlCommand myCommand = new SqlCommand();
    SqlTransaction myTrans;

    myTrans = myConnection.BeginTransaction(IsolationLevel.ReadCommitted,"SampleTransaction");
    myCommand.Connection = myConnection;
    myCommand.Transaction = myTrans;

    try
    {
      myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
      myCommand.ExecuteNonQuery();
      myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
      myCommand.ExecuteNonQuery();
      myTrans.Commit();
      Console.WriteLine("Both records are written to database.");
    }
    catch(Exception e)
    {
      myTrans.Rollback("SampleTransaction");
      Console.WriteLine(e.ToString());
      Console.WriteLine("Neither record was written to database.");
    }
    finally
    {
      myConnection.Close();
    }
}

你可能感兴趣的:(C#)