sql server , C# 多条语句事务处理,失败回滚
1 public bool mysql() 2 { 3 conn.Open(); 4 SqlTransaction mytran = conn.BeginTransaction();//形如数据事务 5 SqlCommand cmd; 6 try 7 { 8 string sql = "********";//sql语句1 9 cmd = new SqlCommand(sql, conn); 10 cmd.Transaction = mytran; 11 cmd.ExecuteNonQuery(); 12 13 sql = "*****";//sql语句2 14 cmd = new SqlCommand(sql, conn); 15 cmd.Transaction = mytran; 16 cmd.ExecuteNonQuery(); 17 18 mytran.Commit();//提交数据库事务 19 return true; 20 } 21 catch (Exception ex) 22 { 23 mytran.Rollback();//回滚(出错的时候) 24 return false; 25 } 26 finally 27 { 28 conn.Close(); 29 } 30 }