VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之使用C# 操作存储过程,执行sql语句通用类

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

    /// <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}】\n 异常原因:【{e.Message}】\n 异常详细信息:【{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}】\n 异常原因:【{e.Message}】\n 异常详细信息:【{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}】\n 异常原因:【{e.Message}】\n 异常详细信息:【{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.......................
我爱代码,代码使我快乐!

相关教程