怎样使用事物 执行4个sql 而且着4个sql是处理4个不同的表 我是用三层架构做的
------解决方案--------------------------------------------------------
http://www.cnblogs.com/yyl8781697/archive/2012/02/01/SqlTransaction
小弟写的,希望对LZ有帮助
------解决方案--------------------------------------------------------
一个sql不成功就回滚?
还是4个其中某一个不成功就回滚?
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
- C# code
#region 事务执行 /// <summary> /// 执行事务 /// </summary>张辉 2011.09.21 /// <param name="cmdList">需要按事务执行的Sql语句集合</param> /// <returns>返回true:执行成功;返回false:执行失败</returns> public static bool ExecuteTran(List<string> cmdList) { bool mark = false; using (SqlConnection con = new SqlConnection(connString)) { if (con.State != ConnectionState.Open) con.Open(); SqlTransaction tran = con.BeginTransaction(); try { SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.Transaction = tran; foreach (string item in cmdList) { cmd.CommandText = item; cmd.ExecuteNonQuery(); } mark = true; tran.Commit(); } catch (Exception ex) { PubFunction.ErrorLogPrint("事务执行", ex.Message); tran.Rollback(); } return mark; } } /// <summary> /// 执行事务,可自定义连接字符串 /// </summary>张辉 2011.09.21 /// <param name="cmdList">需要按事务执行的Sql语句集合</param> /// <param name="conStr">自定义的连接字符串</param> /// <returns>返回true:执行成功;返回false:执行失败</returns> public static bool ExecuteTran(List<string> cmdList, string conStr) { using (SqlConnection myCon = new SqlConnection(conStr)) { bool mark = false; if (myCon.State != ConnectionState.Open) myCon.Open(); SqlTransaction tran = myCon.BeginTransaction(); try { SqlCommand cmd = new SqlCommand(); cmd.Connection = myCon; cmd.Transaction = tran; foreach (string item in cmdList) { cmd.CommandText = item; cmd.ExecuteNonQuery(); } mark = true; tran.Commit(); } catch (Exception ex) { PubFunction.ErrorLogPrint("事务执行", ex.Message); tran.Rollback(); } return mark; } } /// <summary> /// 带参数的存储过程执行 /// </summary>张辉 2011.09.28 添加 /// <param name="cmdList">执行命令和参数列表集合列表</param> /// <returns>true:执行成功 false:执行失败</returns> public static bool ExecuteTran(List<SqlStrWithParameter> cmdList) { bool mark = false; using (SqlConnection con = new SqlConnection(connString)) { if (con.State != ConnectionState.Open) con.Open(); SqlTransaction tran = con.BeginTransaction(); try { SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.Transaction = tran; foreach (SqlStrWithParameter item in cmdList) { cmd.Dispose(); cmd.CommandText = item.SqlStr; if (item.Parameters != null && item.Parameters.Length > 0) { foreach (SqlParameter p in item.Parameters) { cmd.Parameters.Add(p); } } cmd.ExecuteNonQuery(); } mark = true; tran.Commit(); } catch (Exception ex) { PubFunction.ErrorLogPrint("事务执行", ex.Message); tran.Rollback(); } return mark; } } #endregion