ado.net 中事務的使用
阿新 • • 發佈:2018-12-02
list date close tid com conn HERE lose gin
SqlHelper 類方法中啟用事務
1 public static int UpdateByTran(List<string> sqlList) 2 { 3 SqlConnection conn = new SqlConnection(connString); 4 SqlCommand cmd = new SqlCommand(); 5 cmd.Connection = conn; 6 try 7 { 8 conn.Open();9 cmd.Transaction = conn.BeginTransaction();//開啟事務 10 int result = 0; 11 foreach (string sql in sqlList) 12 { 13 cmd.CommandText = sql; 14 result += cmd.ExecuteNonQuery(); 15 } 16 cmd.Transaction.Commit();//提交事務 17 return result; 18 } 19 catch (Exception ex) 20 { 21 //寫入日誌... 22 if (cmd.Transaction != null) 23 cmd.Transaction.Rollback();//回滾事務 24 throw new Exception("調用事務更新方法時出現異常:" + ex.Message);25 } 26 finally 27 { 28 if (cmd.Transaction != null) 29 cmd.Transaction = null;//清除事務 30 conn.Close(); 31 } 32 }
調用
1 static void Main(string[] args) 2 { 3 List<string> sqlList = new List<string>() 4 { 5 "delete from ScoreList where StudentId=100013", 6 "delete from ScoreList where StudentId=100014", 7 "delete from ScoreList where StudentId=100011", 8 9 "delete from Students where StudentId=100010", 10 "delete from Students where StudentId=100013", 11 "delete from Students where StudentId=100014", 12 "delete from Students where StudentId=100011", 13 }; 14 string sql = "select count(*) from Students"; 15 Console.WriteLine("刪除前學生總數:{0}", SQLHelper.GetSingleResult(sql).ToString()); 16 Console.WriteLine("------------------------------------------------------------"); 17 int result = 0; 18 try 19 { 20 result = SQLHelper.UpdateByTran(sqlList); 21 } 22 catch (Exception ex) 23 { 24 Console.WriteLine(ex.Message); 25 Console.WriteLine("------------------------------------------------------------"); 26 } 27 if (result > 0) 28 Console.WriteLine("刪除成功!"); 29 else 30 Console.WriteLine("刪除失敗!"); 31 Console.WriteLine("------------------------------------------------------------"); 32 Console.WriteLine("刪除後學生總數:{0}", SQLHelper.GetSingleResult(sql).ToString()); 33 Console.ReadLine(); 34 }
ado.net 中事務的使用