欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 启用事务提交多条带参数的SQL语句实例代码

程序员文章站 2023-12-19 16:42:58
具体代码如下所示: /// /// 启用事务提交多条带参数的sql语句 /// ...

具体代码如下所示:

/// <summary>
 /// 启用事务提交多条带参数的sql语句
 /// </summary>
 /// <param name="mainsql">主表sql</param>
 /// <param name="mainparam">主表对应的参数</param>
 /// <param name="detailsql">明细表sql语句</param>
 /// <param name="detailparam">明细表对应的参数</param>
 /// <returns>返回事务是否成功</returns>
 public static bool updatebytran(string mainsql, sqlparameter[] mainparam, string detailsql, list<sqlparameter[]> detailparam)
 {
  sqlconnection conn = new sqlconnection(connstring);
  sqlcommand cmd = new sqlcommand();
  cmd.connection = conn;
  try
  {
   conn.open();
   cmd.transaction = conn.begintransaction();//开启事务
   if (mainsql != null && mainsql.length != 0)
   {
    cmd.commandtext = mainsql;
    cmd.parameters.addrange(mainparam);
    cmd.executenonquery();
   }
   foreach (sqlparameter[] param in detailparam)
   {
    cmd.commandtext = detailsql;
    cmd.parameters.clear();
    cmd.parameters.addrange(param);
    cmd.executenonquery();
   }
   cmd.transaction.commit();//提交事务
   return true;
  }
  catch (exception ex)
  {
   if (cmd.transaction != null)
   {
    cmd.transaction.rollback();//回滚事务
   }
   //将异常信息写入日志
   string errorinfo = "调用updatebytran(string mainsql, sqlparameter[] mainparam,string detailsql ,list <sqlparameter []>detailparam)方法时<br data-filtered="filtered">发生错误,具体信息:" + ex.message;
   writelog(errorinfo);
   throw ex;
  }
  finally
  {
   if (cmd.transaction != null)
   {
    cmd.transaction = null;//清空事务
   }
   conn.close();
  }
 }

总结

以上所述是小编给大家介绍的c# 启用事务提交多条带参数的sql语句,希望对大家有所帮助

上一篇:

下一篇: