• C#执行存储过程


    闲话不多说,直接上代码:

        /// <summary>
        /// Sql通用类
        /// </summary>
        public class SqlHelper
        {
           首先配置连接字符串
            public static string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;//ConnString表示webconfig中的连接字符串
     
           执行存储过程不设置超时时间
            /// <summary>
            /// 调用存储过程
            /// </summary>
            /// <param name="connStr">连接字符串</param>
            /// <param name="storedProcedureName">存储过程名称</param>
            /// <param name="ResponseBool">存储过程执行状态</param>
            /// <param name="ResponseMsg">执行存储过程状态描述</param>
            /// <param name="paramsObject">存储过程输入参数</param>
            /// <returns></returns>
            public static DataSet Sql_GetStoredProcedureFunction(string connStr, string storedProcedureName, out bool ResponseBool, out string ResponseMsg, params ParameterKeyValuesEntity[] paramsObject)
            {
                DataSet ResponseDs = new DataSet();
                ResponseBool = true;
                ResponseMsg = "获取成功!";
                try
                {
                    using (SqlConnection sqlConn = new SqlConnection(connStr))
                    {
                        sqlConn.Open();
                        using (SqlCommand sqlCmd = new SqlCommand(storedProcedureName, sqlConn))
                        {
                            sqlCmd.CommandType = CommandType.StoredProcedure;
                            if (paramsObject.Count() > 0)
                            {
                                for (int i = 0; i < paramsObject.Count(); i++)
                                {
                                    SqlParameter sqlParameter = new SqlParameter(paramsObject[i].Key, paramsObject[i].Value);
                                    sqlCmd.Parameters.Add(sqlParameter);
                                }
                            }
                            SqlDataAdapter sda = new SqlDataAdapter(sqlCmd);
                            sda.Fill(ResponseDs);
                        }
                    }
                }
                catch (Exception e)
                {
                    ResponseBool = false;
                    ResponseMsg = $"查询存储过程时出现异常,存储过程:【{storedProcedureName}】 异常原因:【{e.Message}】 异常详细信息:【{e.StackTrace}】!";
                }
                return ResponseDs;
            }
     
            当存储过程执行时间太长时,存储过程的默认超时时间是30s,需要设置存储过程执行超时时间
            /// <summary>
            /// 调用存储过程  (自定义超时时间)
            /// </summary>
            /// <param name="connStr">连接字符串</param>
            /// <param name="storedProcedureName">存储过程名称</param>
            /// <param name="commandOutTime">执行存储过程请求超时时间(单位:s)</param>
            /// <param name="ResponseBool">存储过程执行状态</param>
            /// <param name="ResponseMsg">执行存储过程状态描述</param>
            /// <param name="paramsObject">存储过程输入参数</param>
            /// <returns></returns>
            public static DataSet Sql_GetStoredProcedureFunction(string connStr, string storedProcedureName, int commandOutTime, out bool ResponseBool, out string ResponseMsg, params ParameterKeyValuesEntity[] paramsObject)
            {
                DataSet ResponseDs = new DataSet();
                ResponseBool = true;
                ResponseMsg = "获取成功!";
                try
                {
                    using (SqlConnection sqlConn = new SqlConnection(connStr))
                    {
                        sqlConn.Open();
                        using (SqlCommand sqlCmd = new SqlCommand(storedProcedureName, sqlConn))
                        {
                            sqlCmd.CommandType = CommandType.StoredProcedure;
                            sqlCmd.CommandTimeout = commandOutTime;
                            if (paramsObject.Count() > 0)
                            {
                                SqlParameter[] sqlParameters = new SqlParameter[paramsObject.Count()];
                                for (int i = 0; i < paramsObject.Count(); i++)
                                {
                                    SqlParameter sqlParameter = new SqlParameter(paramsObject[i].Key, paramsObject[i].Value);
                                    sqlCmd.Parameters.Add(sqlParameter);
                                }
                            }
                            SqlDataAdapter sda = new SqlDataAdapter(sqlCmd);
                            sda.Fill(ResponseDs);
                        }
                    }
                }
                catch (Exception e)
                {
                    ResponseBool = false;
                    ResponseMsg = $"查询存储过程时出现异常,存储过程:【{storedProcedureName}】 异常原因:【{e.Message}】 异常详细信息:【{e.StackTrace}】!";
                }
                return ResponseDs;
            }
     
            执行sql语句,进行增删改操作
            /// <summary>
            /// 增删改数据
            /// </summary>
            /// <param name="sqlConnStr, ">数据库连接字符串</param>
            /// <param name="sql">执行的sql语句</param>
            /// <param name="paramsObject">输入参数</param>
            /// <returns></returns>
            public static int SQLExecuteData(string sqlConnStr, string sql, params ParameterKeyValuesEntity[] paramsObject)
            {
                int count = 0;
                using (SqlConnection conn = new SqlConnection(sqlConnStr))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(sql, conn); //定义一个sql操作命令对象
                    if (paramsObject.Count() > 0)
                    {
                        for (int i = 0; i < paramsObject.Count(); i++)
                        {
                            SqlParameter sqlParameter = new SqlParameter(paramsObject[i].Key, paramsObject[i].Value);
                            cmd.Parameters.Add(sqlParameter);
                        }
                    }
                    count = cmd.ExecuteNonQuery(); //执行语句
                    conn.Close(); //关闭连接
                    cmd = null;
                    conn.Dispose(); //释放对象
                }
                return count;
            }
     
          当数据库中表关系及其复杂,并且数据量特别多的时候(一般情况下用缓存解决问题),执行sql查询语句相当耗时,需要设置sql语句请求超时时间。
          执行sql查询语句,设置sql查询语句超时时间
            /// <summary>
            /// 执行SQL脚本
            /// </summary>
            /// <param name="connStr">连接字符串</param>
            /// <param name="sqlScript">SQL脚本</param>
            /// <param name="ResponseBool">执行状态</param>
            /// <param name="ResponseMsg">状态描述</param>
            /// <param name="commandOutTime">执行sql语句请求超时时间(单位:s)</param>
            /// <param name="paramsObject">输入参数</param>
            /// <returns></returns>
            public static DataSet Sql_GetStored(string connStr, string sqlScript, out bool ResponseBool, out string ResponseMsg, int commandOutTime = 500, params ParameterKeyValuesEntity[] paramsObject)
            {
                DataSet ResponseDs = new DataSet();
                ResponseBool = true;
                ResponseMsg = "获取成功!";
                try
                {
                    using (SqlConnection sqlConn = new SqlConnection(connStr))
                    {
                        sqlConn.Open();
                        using (SqlCommand sqlCmd = new SqlCommand(sqlScript, sqlConn))
                        {
                            sqlCmd.CommandType = CommandType.Text;
                            sqlCmd.CommandTimeout = commandOutTime;
                            if (paramsObject.Count() > 0)
                            {
                                for (int i = 0; i < paramsObject.Count(); i++)
                                {
                                    SqlParameter sqlParameter = new SqlParameter(paramsObject[i].Key, paramsObject[i].Value);
                                    sqlCmd.Parameters.Add(sqlParameter);
                                }
                            }
                            SqlDataAdapter sda = new SqlDataAdapter(sqlCmd);
                            sda.Fill(ResponseDs);
                        }
                    }
                }
                catch (Exception e)
                {
                    ResponseBool = false;
                    ResponseMsg = $"查询存储过程时出现异常,SQL脚本:【{sqlScript}】 异常原因:【{e.Message}】 异常详细信息:【{e.StackTrace}】!";
                }
                return ResponseDs;
            }
        
        入参实体建类
        /// <summary>
        /// 输入参数实体   参数名称(Key)/参数值(Value)
        /// </summary>
        public class ParameterKeyValuesEntity
        {
            /// <summary>
            /// 参数名称
            /// </summary>
            public string Key { get; set; }
            /// <summary>
            /// 参数值
            /// </summary>
            public object Value { get; set; }
        }
     
     
     
     
     
     执行存储过程示例:
     public Result 方法名(string 入参1,string 入参2, string 入参3)
            {
                try
                {             
                    //定义输出参数
                    Result result = new Result();
                    //存储过程名称
                    string procName = "存储过程名称";
                    #region -- 执行存储过程获取数据
                    //返回值状态
                    bool responseBool = true;
                    //返回值状态描述
                    string responseMsg = string.Empty;
                    //存储过程输入参数实体
                    ParameterKeyValuesEntity[] parameterKeyValue = new ParameterKeyValuesEntity[]
                    {
                    new ParameterKeyValuesEntity(){Key="@存储过程入参1",Value=赋值1},
                    new ParameterKeyValuesEntity(){Key="@存储过程入参2",Value=赋值2},
                    new ParameterKeyValuesEntity(){Key="@存储过程入参3",Value=赋值3},         
                    };
                    //使用sql通用类的方法执行存储过程
                    DataSet ds = SqlHelper.Sql_GetStoredProcedureFunction(connStr, procName, out responseBool, out responseMsg, parameterKeyValue);
                    if (!responseBool)
                    {
                        result.code = "204";
                        result.msg = $"查询存储过程时出现异常,异常信息:{responseMsg}";
                        ExceptionLogHelper.WriteLog($"业务异常:存储过程名:{procName}---异常信息:{responseMsg}");//项目中的异常日志
                        return result;
                    }
                    DataTable dt = ds.Tables[0];             
                    if (dt != null && dt.Rows != null && dt.Rows.Count > 0)
                    {
                        获取存储过程执行后的数据,给实体类赋值
                    }
                    #endregion
                    result.data = loopbackdata;
                    string json = JsonConvert.SerializeObject(result.data);
                    result = ResultHelper.ReturnResultSuccess(json, typeof(JObject));
                    return result;
                }
                catch (Exception e)
                {
                    ExceptionLogHelper.WriteLog($"业务异常:{e}");
                    return ResultHelper.ReturnResultError($"异常信息:{e}");
                }
            }
     
           The END.......................
  • 相关阅读:
    验证码
    SQL给字段加上统一的某个字符
    科讯CMS V9标签清单
    需要重新启动计算机.必须重新启动计算机才能安装 SQL Server
    父页面iframe自动适应子页面的宽高度
    div随另一个div自动增高
    让图片在DIV中垂直居中
    nginx default server
    zabbix proxy 分布式监控
    openjdk tomcat 安装
  • 原文地址:https://www.cnblogs.com/qiu18359243869/p/10642207.html
Copyright © 2020-2023  润新知