C#下应用事务循环操作Sql语句
1 /// <summary> 2 /// 执行多条Sql语句,实现事务回滚 3 /// </summary> 4 /// <param name="SQLStringList">sql语句集合</param>
5 /// <param name="ErrorMsg">执行多SQL语句事务,返回错误信息</param>
6 /// <returns></returns>
7 public static bool SqlTransSqlStr(List<string> SQLStringList, ref string ErrorMsg) 8 { 9 bool i = false; 10 string connectionString = ConfigurationManager.ConnectionStrings["demo"].ConnectionString; 11 using (SqlConnection connection = new SqlConnection(connectionString)) 12 { 13 connection.Open(); 14 SqlCommand cmd = new SqlCommand(); 15 cmd.Connection = connection; 16 SqlTransaction tx = connection.BeginTransaction(); 17 cmd.Transaction = tx; 18 try 19 { 20 for (int n = 0; n < SQLStringList.Count; n++) 21 { 22 string strsql = SQLStringList[n].ToString(); 23 if (strsql.Trim().Length > 1) 24 { 25 cmd.CommandText = strsql; 26 cmd.ExecuteNonQuery(); 27 cmd.Parameters.Clear(); 28 } 29 } 30 tx.Commit(); 31 i = true; 32 } 33 catch (System.Data.SqlClient.SqlException E) 34 { 35 tx.Rollback(); 36 ErrorMsg = E.Message; 37 i = false; 38 } 39 } 40 return i; 41 }
直接代码,改一下配置文件里面的字符串的名字就OK 了。