namespace _0001_SQLTransaction { class SQLHelper { public static int UpdateByTrans(List sqlList) { string connString = "server=.;database=StudentManager;Uid=sa;pwd=password01!"; SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; try { conn.Open(); cmd.Transaction = conn.BeginTransaction();//开启事务 int result = 0; foreach (string sql in sqlList) { cmd.CommandText = sql; result += cmd.ExecuteNonQuery();//执行语句 } cmd.Transaction.Commit();//提交事务 return result; } catch (Exception ex) { //log/... if (cmd.Transaction != null) { cmd.Transaction.Rollback(); } throw new Exception("调用事务更新方法时候出现异常!" + ex.Message); } finally { if (cmd.Transaction != null) { cmd.Transaction = null;//清除事务,一定要清除 } conn.Close(); } } } }