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

posted on 2006-04-18 11:47  独蠢无双  阅读(714)  评论(0编辑  收藏  举报