C# 用批处理执行事务

 有时候写一些操作数据库是,要执行多条Sql语句,不得不用事务处理。

用程式方法:

public static bool ExecuteSqlTransaction(ArrayList list)
{
bool yes = false;
using (SqlConnection con = new SqlConnection(_ConnectString))
{
con.Open();
using (SqlTransaction trans = con.BeginTransaction())
{
try
{
for (int i = 0; i < list.Count; i++)
{
SQLHelper.ExecuteNonQuery(trans, CommandType.Text, list[i].ToString());
}

if (trans != null)
{
trans.Commit();
yes= true;
}

}
catch (Exception ex)
{
trans.Rollback();
yes = false;
throw ex;
}
finally
{

con.Close();
}

}

}

return yes;

}

这个方法很简单,但效率不高。

后来多方思考用C# 批处理的方法,更好用。

ArrayList Sqllist = new ArrayList();

string strCreateProc = "";

                    strCreateProc = strCreateProc + "  begin tran test \n ";

                    for (int s = 0; s < Sqllist.Count; s++)

                    {

                        strCreateProc = strCreateProc + "\n       " + Sqllist[s].ToString() + " ;";

                    }

                    strCreateProc = strCreateProc + " \n         if @@error<>0 \n           begin \n            rollback tran test \n           end  \n           else \n            begin \n            commit tran test \n            end  ";

                   

                    string reSql = strCreateProc;

                    int ok = SQLHelper.ExecuteNonQuery(_ConnectString, CommandType.Text, reSql);

原文地址:https://www.cnblogs.com/aran/p/2917413.html