try catch 多条语句事务处理,失败回滚

List<string> sqllist = new List<string>();

string grade_sqlCmd ="";

sqllist.Add(grade_sqlCmd);

using (SqlConnection connection = new SqlConnection(SQLHelper.NukeDBConnectionString))

{

   connection.Open();

   SqlCommand cmd = new SqlCommand();

   cmd.Connection = connection;

   SqlTransaction tx = connection.BeginTransaction();

   cmd.Transaction = tx;

   try

   {

    for (int n = 0; n < sqllist.Count; n++)

    {

      string strsql = sqllist[n];

      if (strsql.Trim().Length > 1)

      {

        cmd.CommandText = strsql;

        cmd.ExecuteNonQuery();

       }

     }

     tx.Commit();//执行事务

     return new ExecResultData(true);

    }

    catch

    {

       tx.Rollback(); //回滚事务

       return new ExecResultData("执行失败");

    }

    finally

    {

       cmd.Dispose();

       connection.Close();

    }

}

猜你喜欢

转载自blog.csdn.net/oYuHuaChen/article/details/94736381
今日推荐