c# 之 事务

SqlTransaction事务的简单例子

{   
                          DataTable   dt   =   new   DataTable();   
                          System.Data.SqlClient.SqlConnection   cnn   =   new   System.Data.SqlClient.SqlConnection("连接字符串");  
                          System.Data.SqlClient.SqlCommand   cm   =   new   System.Data.SqlClient.SqlCommand();  
                          cm.Connection   =   cnn;  
                          cnn.Open();  
                          System.Data.SqlClient.SqlTransaction   trans   =   cnn.BeginTransaction();  
                          try  
                          {  
                                  foreach(DataRow   dr   in   dt.Rows)  
                                  {  
                                          cm.CommandText   =   "update   [表]   set   [数量]   =   @amount   where   productID   =   @productID";  
                                          cm.Parameters.Add("@amount",SqlDbType.Int);  
                                          cm.Parameters["@amount"].Value   =   Convert.ToInt32(dr["amount"]);  
                                          cm.Parameters.Add("@productID",SqlDbType.VarChar);  
                                          cm.Parameters["@productID"].Value   =   dr["productID"].ToString();  
                                          cm.ExecuteNonQuery();  
                                  }  
                                  trans.Commit();  
                          }  
                          catch  
                          {  
                                  trans.Rollback();  
                          }  
                          finally  
                          {  
                                  cnn.Close();  
                                  trans.Dispose();  
                                  cnn.Dispose();  
                          }  
                  }

 

posted @ 2017-06-27 09:32  zmztyas  阅读(170)  评论(0编辑  收藏  举报