日期:2014-05-16 浏览次数:20501 次
实际项目中我们经常遇到要批量执行多条sql语句实现实现数据库事务 !
下么就是批量执行多条sql语句实现实现数据库事务胡代码:这里分为两种方式分别如下 :
--------方式1-------------
/// <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; } } } }就这么简单!