• C# 启用事务提交多条带参数的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)方法时
    发生错误,具体信息:" + ex.Message; WriteLog(errorInfo); throw ex; } finally { if (cmd.Transaction != null) { cmd.Transaction = null;//清空事务 } conn.Close(); } }

    转载自CSDN

  • 相关阅读:
    Linux 忘记root密码
    Linux 基础命令
    Linux 运行级别
    Oracle 体系结构
    Oracle 数据库启动过程
    数据库设计范式
    Oracle通过ROWID删除表中重复记录
    JACASCRIPT--的奇技技巧的44招
    css 的小细节,小总结
    关于我们DOM的知识点
  • 原文地址:https://www.cnblogs.com/ZeedLee/p/8482185.html
Copyright © 2020-2023  润新知