方法一:
/// <summary>
/// 执行多条SQL语句,实现数据库事务 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> /// <returns>执行事务影响的行数</returns> public static int ExecuteSqlTran(string connectionString, List<String> SQLStringList) { using (SqlConnection conntion = new SqlConnection(connectionString)) { conntion.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conntion;SqlTransaction ts = conntion.BeginTransaction();
cmd.Transaction = ts; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } ts.Commit();//提交数据库事务 return count; } catch { ts.Rollback(); return 0; } } }方法二:
/// <summary>
/// 执行多条SQL语句,实现数据库事务 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public static void ExecuteSqlTran(string connectionString, Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { //循环 foreach (DictionaryEntry myDY in SQLStringList) { string cmdText = myDY.Key.ToString(); SqlParameter[] parameter = (SqlParameter[])myDY.Value; PrepareCommand(cmd, conn, trans, cmdText, parameter); int result = cmd.ExecuteNonQuery(); //这里可以记录该事务的执行结果 cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } }