SqlConnection   myConnection   =   new   SqlConnection("server=(local)\\NetSDK;Trusted_Connection=yes;database=northwind");  
          SqlCommand   myCommand   =   new   SqlCommand();  
          SqlTransaction   myTrans;  
   
          //   Open   the   connection.  
          myConnection.Open();  
   
          //   Assign   the   connection   property.  
          myCommand.Connection     =   myConnection;  
   
          //   Begin   the   transaction.  
          myTrans   =   myConnection.BeginTransaction();  
   
          //   Assign   transaction   object   for   a   pending   local   transaction  
          myCommand.Transaction   =   myTrans;  
   
          try  
          {  
              //   Restore   database   to   near   it's   original   condition   so   sample   will   work   correctly.  
              myCommand.CommandText   =   "DELETE   FROM   Region   WHERE   (RegionID   =   100)   OR   (RegionID   =   101)";  
              myCommand.ExecuteNonQuery();  
   
              //   Insert   the   first   record.  
              myCommand.CommandText   =   "Insert   into   Region   (RegionID,   RegionDescription)   VALUES   (100,   'MidWestern')";  
              myCommand.ExecuteNonQuery();  
   
              //   Insert   the   second   record.  
              myCommand.CommandText   =   "Insert   into   Region   (RegionID,   RegionDescription)   VALUES   (101,   'MidEastern')";  
              myCommand.ExecuteNonQuery();  
   
              myTrans.Commit();  
              Console.WriteLine("Both   Records   are   written   to   the   database!");  
          }  
          catch(Exception   e)  
          {  
              myTrans.Rollback();  
              Console.WriteLine(e.ToString());  
              Console.WriteLine("Neither   record   is   written   to   the   database!");  
          }  
          finally  
          {  
              myConnection.Close();  
          }

posted on 2008-11-19 22:24  来彬  阅读(308)  评论(0编辑  收藏  举报