SQL Server数据库连接类SQLHelper.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Data.Common;

namespace SWDataDB.DAL
{
    public class SQLHelper
    {
        /// <summary>
        /// The SqlHelper class is intended to encapsulate high performance, 
        /// scalable best practices for common uses of SqlClient.
        /// </summary>


        //Database connection strings
        public static readonly string SQLConnString = ConfigurationManager.ConnectionStrings["SQLConnString"].ConnectionString;
        //public static readonly string SQLBookConnString = ConfigurationManager.ConnectionStrings["SQLBookConnString"].ConnectionString;
        // Hashtable to store cached parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                cmd.CommandTimeout = 999;
                int val = cmd.ExecuteNonQuery();

                cmd.Parameters.Clear();
                return val;
            }
        }

        public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                DataSet data = new DataSet();
                ad.Fill(data);
                cmd.Parameters.Clear();
                return data;
            }
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            cmd.CommandTimeout = 999;
            int val = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">an existing sql transaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            cmd.CommandTimeout = 999;
            int val = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();
            return val;
        }
        /// <summary>
        /// 获得datatable
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataTable ExecuteReaderDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            DataSet dataset = new DataSet();
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataAdapter adapter = new SqlDataAdapter(cmdText, conn);

                adapter.Fill(dataset);
                cmd.CommandTimeout = 999;
                cmd.Parameters.Clear();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }

            return dataset.Tables[0];
        }
        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                cmd.CommandTimeout = 999;
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                cmd.CommandTimeout = 999;
                object val = cmd.ExecuteScalar();

                cmd.Parameters.Clear();
                return val;
            }
        }



        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            cmd.CommandTimeout = 999;
            object val = cmd.ExecuteScalar();

            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        /// <summary>
        /// 单表(视图)获取分页SQL语句
        /// </summary>
        /// <param name="tableName">表名或视图名</param>
        /// <param name="key">唯一键</param>
        /// <param name="fields">获取的字段</param>
        /// <param name="condition">查询条件(不包含WHERE)</param>
        /// <param name="collatingSequence">排序规则(不包含ORDER BY)</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="pageIndex">页码(从1开始)</param>
        /// <returns>分页SQL语句</returns>
        public static string GetPagingSQL(
            string tableName,
            string key,
            string fields,
            string condition,
            string collatingSequence,
            long pageSize,
            long pageIndex)
        {
            string whereClause = string.Empty;
            if (!string.IsNullOrEmpty(condition))
            {
                whereClause = string.Format("WHERE {0}", condition);
            }

            if (string.IsNullOrEmpty(collatingSequence))
            {
                collatingSequence = string.Format("{0} ASC", key);
            }

            StringBuilder sbSql = new StringBuilder();

            sbSql.AppendFormat("SELECT  {0} ", PrependTableName(tableName, fields, ','));
            sbSql.AppendFormat("FROM    ( SELECT TOP {0} ", pageSize * pageIndex);
            sbSql.AppendFormat("                    [_RowNum_] = ROW_NUMBER() OVER ( ORDER BY {0} ), ", collatingSequence);
            sbSql.AppendFormat("                    {0} ", key);
            sbSql.AppendFormat("          FROM      {0} ", tableName);
            sbSql.AppendFormat("          {0} ", whereClause);
            sbSql.AppendFormat("        ) AS [_TempTable_] ");
            sbSql.AppendFormat("        INNER JOIN {0} ON [_TempTable_].{1} = {0}.{1} ", tableName, key);
            sbSql.AppendFormat("WHERE   [_TempTable_].[_RowNum_] > {0} ", pageSize * (pageIndex - 1));
            sbSql.AppendFormat("ORDER BY [_TempTable_].[_RowNum_] ASC ");

            return sbSql.ToString();
        }

        /// <summary>
        /// 给字段添加表名前缀
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="fields">字段</param>
        /// <param name="separator">标识字段间的分隔符</param>
        /// <returns></returns>
        public static string PrependTableName(string tableName, string fields, char separator)
        {
            StringBuilder sbFields = new StringBuilder();

            string[] fieldArr = fields.Trim(separator).Split(separator);
            foreach (string str in fieldArr)
            {
                sbFields.AppendFormat("{0}.{1}{2}", tableName, str.Trim(), separator);
            }

            return sbFields.ToString().TrimEnd(separator);
        }

        /*
        nzperfect [no_mIss] 高效通用分页存储过程(双向检索) 2007.5.7  QQ:34813284
        敬告:适用于单一主键或存在唯一值列的表或视图
        ps:Sql语句为8000字节,调用时请注意传入参数及sql总长度不要超过指定范围
         * 

        @TableName VARCHAR(200),     --表名
        @FieldList VARCHAR(2000),    --显示列名,如果是全部字段则为*
        @PrimaryKey VARCHAR(100),    --单一主键或唯一值键
        @Where VARCHAR(2000),        --查询条件 不含'where'字符,如id>10 and len(userid)>9
        @Order VARCHAR(1000),        --排序 不含'order by'字符,如id asc,userid desc,必须指定asc或desc                                 
                                     --注意当@SortType=3时生效,记住一定要在最后加上主键,否则会让你比较郁闷
        @SortType INT,               --排序规则 1:正序asc 2:倒序desc 3:多列排序方法
        @RecorderCount INT,          --记录总数 0:会返回总记录
        @PageSize INT,               --每页输出的记录数
        @PageIndex INT,              --当前页数
        @TotalCount INT OUTPUT,      --记返回总记录
        @TotalPageCount INT OUTPUT   --返回总页数
        */
        /// <summary>
        /// 调用存储过程 分页查询
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="FieldList">显示列名,如果是全部字段则为*</param>
        /// <param name="PrimaryKey">单一主键或唯一值键</param>
        /// <param name="Where">查询条件 不含'where'字符,如id>10 and len(userid)>9</param>
        /// <param name="Order">排序 不含'order by'字符,如id asc,userid desc,必须指定asc或desc</param>
        /// <param name="SortType">排序规则</param>
        /// <param name="RecorderCount">记录总数</param>
        /// <param name="PageSize">每页输出的记录数</param>
        /// <param name="PageIndex">当前页数</param>
        /// <param name="TotalCount">记返回总记录</param>
        /// <param name="TotalPageCount">返回总页数</param>
        /// <returns></returns>
        public static DataSet P_viewPage(string TableName, string FieldList, string PrimaryKey, string Where, string Order,
                                int SortType, int RecorderCount, int PageSize, int PageIndex, out int TotalCount, out int TotalPageCount)
        {
            string strSql = "P_viewPage";
            int totalCount = 0;
            int totalPageCount = 0;

            SqlParameter[] arrSqlPara = new SqlParameter[]
           {

               new SqlParameter("@TableName",TableName),
               new SqlParameter("@FieldList",FieldList),
               new SqlParameter("@PrimaryKey",PrimaryKey),
               new SqlParameter("@Where",Where),
               new SqlParameter("@Order",Order),
               new SqlParameter("@SortType",SortType),
               new SqlParameter("@RecorderCount",RecorderCount),
               new SqlParameter("@PageSize",PageSize),
               new SqlParameter("@PageIndex",PageIndex),
               new SqlParameter("@TotalCount",totalCount),
               new SqlParameter("@TotalPageCount",totalPageCount),

           };

            arrSqlPara[9].Direction = ParameterDirection.Output;
            arrSqlPara[10].Direction = ParameterDirection.Output;

           DataSet ds = SQLHelper.ExecuteDataSet(SQLHelper.SQLConnString, CommandType.StoredProcedure, strSql, arrSqlPara);

           TotalCount = int.Parse(arrSqlPara[9].Value.ToString());
           TotalPageCount = int.Parse(arrSqlPara[10].Value.ToString());

           return ds;

            //return SQLHelper.ExecuteNonQuery(SQLHelper.SQLConnString, CommandType.StoredProcedure, strSql, arrSqlPara);
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iTraveling

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值