码迷,mamicode.com
首页 > Web开发 > 详细

基于Jquery+Ajax+Json+存储过程 高效分页

时间:2018-03-01 17:34:00      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:str   tab   param   focus   font   isnull   检查   exce   nbsp   

在做后台开发中,都会有大量的列表展示,下面给大家给大家分享一套基于Jquery+Ajax+Json+存储过程高效分页列表,只需要传递几个参数即可。当然代码也有改进的地方,如果大家有更好的方法,愿留下宝贵的建议或意见!好了,上代码

存储过程

CREATE PROCEDURE [dbo].[PAGINATION] 
@FEILDS  VARCHAR(1000),--要显示的字段
@PAGE_INDEX INT,--当前页码
@PAGE_SIZE INT,--页面大小
@ORDERTYPE BIT,--当为0时 则为 desc 当为1 时 asc
@ANDWHERE VARCHAR(1000)=‘‘,--where语句 不用加where
@ORDERFEILD VARCHAR(100), --排序的字段
@TableName VARCHAR(100) --查询表名

as
DECLARE @EXECSQL VARCHAR(2000)
DECLARE @ORDERSTR VARCHAR(100)
DECLARE @ORDERBY VARCHAR(100)
BEGIN
    set NOCOUNT on
    IF @ORDERTYPE = 1 
        BEGIN
            SET @ORDERSTR =  > ( SELECT MAX([+@ORDERFEILD+])
            SET @ORDERBY = ORDER BY +@ORDERFEILD+ ASC
        END
    ELSE 
        BEGIN
            SET @ORDERSTR =  < ( SELECT MIN([+@ORDERFEILD+])
            SET @ORDERBY = ORDER BY +@ORDERFEILD+ DESC
        END
    IF @PAGE_INDEX = 1 --当页码是第一页时直接运行,提高速度
        BEGIN
            IF @ANDWHERE=‘‘
                SET @EXECSQL = SELECT TOP +STR(@PAGE_SIZE)+ +@FEILDS+ FROM +@TableName+ +@ORDERBY
            ELSE
                SET @EXECSQL = SELECT TOP +STR(@PAGE_SIZE)+ +@FEILDS+ FROM +@TableName+ WHERE +@ANDWHERE+ + @ORDERBY
        END
    ELSE
        BEGIN
            IF @ANDWHERE=‘‘
                BEGIN      --以子查询结果当做新表时 要给表名别名才能用
                    SET @EXECSQL = SELECT TOP+STR(@PAGE_SIZE)+ +@FEILDS+ FROM +@TableName+ WHERE +@ORDERFEILD+
                                @ORDERSTR+ FROM (SELECT TOP +STR(@PAGE_SIZE*(@PAGE_INDEX-1))+ +@ORDERFEILD+
                                 FROM +@TableName+ +@ORDERBY+) AS TEMP) + @ORDERBY
                END
            ELSE
                BEGIN
                    SET @EXECSQL = SELECT TOP+STR(@PAGE_SIZE)+ +@FEILDS+ FROM +@TableName+ WHERE +@ORDERFEILD+
                                @ORDERSTR+ FROM (SELECT TOP + STR(@PAGE_SIZE*(@PAGE_INDEX-1))+ +@ORDERFEILD+
                                 FROM +@TableName+ WHERE +@ANDWHERE+ +@ORDERBY+) AS TEMP) AND +@ANDWHERE+ + @ORDERBY
                END
        END
EXEC (@EXECSQL)--这里要加括号
END

样式:

<style type="text/css">
a,area   { -moz-outline-style: none;  blr:expression(this.onFocus=this.blur()); text-decoration:none} 
div.badoo { padding:20px; text-align:center; }
div.badoo a { border:1px solid #ededed; padding:10px 13px; color:#333333; border-radius:2px; margin-right:3px;}
div.badoo a:hover {border:1px solid #ff5a00; color: #ff5a00; }
div.badoo a:active {border:1px solid #ff5a00; margin-right:3px;}
div.badoo span { border:1px solid #EDEDED; padding:10px 13px; color:#f00;font-weight:bold;  background:#FAFAFA; border-radius:2px; margin-right:3px;}
div.badoo span.disabled { border:1px solid #EDEDED; padding:10px 13px; color:#000; margin-right:3px; font-weight:100;}
</style>

JS代码

<script type="text/javascript">
       $(function () {
           $.post("GetData.ashx", null, function (data) {
               var total = data;
               PageClick(1, total, 2);
           });
           PageClick = function (pageIndex, total, spanInterval) {
               $.ajax({
                   url: "GetData.ashx",
                   data: { "PageIndex": pageIndex },
                   type: "post",
                   dataType: "json",
                   success: function (data) {
                       //索引从1开始
                       //将当前页索引转为int类型
                       var intPageIndex = parseInt(pageIndex);
                       //获取显示数据的表格
                       var table = $("#content");
                       //清楚表格中内容
                       $("#content tr").remove();
                       //向表格中添加内容
                       for (var i = 0; i < data.length; i++) {
                           table.append(
                               $("<tr><td>" +
                               data[i].id
                               + "</td><td>" +
                               data[i].name
                               + "</td><td>" +
                               data[i].sex
                               + "</td><td>" +
                               data[i].tel
                               + "</td></tr>")
                               );
                       } //for
                       //创建分页
                       //将总记录数结果 得到 总页码数
                       var pageS = total
                       if (pageS % 10 == 0) pageS = pageS / 20;
                       else pageS = parseInt(total / 20) + 1;
                       var $pager = $("#pager");
                       //清楚分页div中的内容
                       $("#pager span").remove();
                       $("#pager a").remove();
                       //添加第一页
                       if (intPageIndex == 1) {
                       //    $pager.append("<span class=‘disabled‘>第一页</span>");
                       }
                       else {
                        //   var first = $("<a href=‘javascript:void(0)‘ first=‘" + 1 + "‘>第一页</a>").click(function () {
                         //      PageClick($(this).attr(‘first‘), total, spanInterval);
                          //     return false;
                        //   });
                        //   $pager.append(first);
                       }
                       //添加上一页
                       if (intPageIndex == 1)
                           $pager.append("<span class=‘disabled‘>上一页</span>");
                       else {
                           var pre = $("<a href=‘javascript:void(0)‘ pre=‘" + (intPageIndex - 1) + "‘>上一页</a>").click(function () {
                               PageClick($(this).attr(‘pre‘), total, spanInterval);
                               return false;
                           });
                           $pager.append(pre);
                       }
                       //设置分页的格式  这里可以根据需求完成自己想要的结果
                       var interval = parseInt(spanInterval); //设置间隔
                       var start = Math.max(1, intPageIndex - interval); //设置起始页
                       var end = Math.min(intPageIndex + interval, pageS)//设置末页
                       if (intPageIndex < interval + 1) {
                           end = (2 * interval + 1) > pageS ? pageS : (2 * interval + 1);
                       }
                       if ((intPageIndex + interval) > pageS) {
                           start = (pageS - 2 * interval) < 1 ? 1 : (pageS - 2 * interval);
                       }
                       //生成页码
                       for (var j = start; j < end + 1; j++) {
                           if (j == intPageIndex) {
                               var spanSelectd = $("<span class=‘current‘>" + j + "</span>");
                               $pager.append(spanSelectd);
                           } //if 
                           else {
                               var a = $("<a href=‘javascript:void(0)‘>" + j + "</a>").click(function () {
                                   PageClick($(this).text(), total, spanInterval);
                                   return false;
                               });
                               $pager.append(a);
                           } //else
                       } //for
                       //上一页
                       if (intPageIndex == Math.ceil(total / 20)) {
                           $pager.append("<span class=‘disabled‘>下一页</span>");
                       }
                       else {
                           var next = $("<a href=‘javascript:void(0)‘ next=‘" + (intPageIndex + 1) + "‘>下一页</a>").click(function () {
                               PageClick($(this).attr("next"), total, spanInterval);
                               return false;
                           });
                           $pager.append(next);
                       }
                       //最后一页
                       if (intPageIndex == pageS) {
                       //    $pager.append("<span class=‘disabled‘>最后一页</span>");
                       }
                       else {
                         //  var last = $("<a href=‘javascript:void(0)‘ last=‘" + pageS + "‘>最后一页</a>").click(function () {
                           //    PageClick($(this).attr("last"), total, spanInterval);
                          //     return false;
                       //    });
                         //  $pager.append(last);
                       }
                   } //sucess
               }); //ajax
           }; //function
       });   //ready
   </script>

Html代码

<table id="content">
</table>
<div id="pager" class="badoo"></div>

.Net后台代码

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Model;



context.Response.ContentType = "text/plain";
            var pageIndex = context.Request["PageIndex"];
            //判断当前索引存不存在,如果不存在则获取记录的总数。
            if (string.IsNullOrEmpty(pageIndex))
            {
                //获取查询记录总数的sql语句
             
                int count = 0;
                int.TryParse(new BLL.t_profit().SelectAllNum(), out count);
                context.Response.Write(count);
                context.Response.End();
            }
            //当根据索引获取数据
            else
            {
                int currentPageIndex = 1;
                int.TryParse(pageIndex, out currentPageIndex);
                SqlParameter[] parms = new SqlParameter[] { 
        new SqlParameter("@FEILDS",SqlDbType.NVarChar,1000),
        new SqlParameter("@PAGE_INDEX",SqlDbType.Int,10),
        new SqlParameter("@PAGE_SIZE",SqlDbType.Int,10),
        new SqlParameter("@ORDERTYPE",SqlDbType.Int,2),
        new SqlParameter("@ANDWHERE",SqlDbType.VarChar,1000),
        new SqlParameter("@ORDERFEILD",SqlDbType.VarChar,100)
        };
                parms[0].Value = "id,name,sex,tel";//获取所有的字段
                parms[1].Value = pageIndex;//当前页面索引
                parms[2].Value = 20;//页面大小
                parms[3].Value = 0;//升序排列
                parms[4].Value = "";//条件语句
                parms[5].Value = "id";//排序字段
                List<Book> list = new List<Book>();
              
                using (SqlDataReader sdr = Yoodor.DAL.SqlHelper.ExecuteReader(CommandType.StoredProcedure, "PAGINATION", parms))
                {
                    while (sdr.Read())
                    {
                        list.Add(new Book { id = sdr[0].ToString(), name = sdr[1].ToString(), sex = sdr[2].ToString(), tel = sdr[3].ToString() });
                    }
                }
                context.Response.Write(new JavaScriptSerializer().Serialize(list).ToString());//转为Json格式
            }




 public string id { get; set; }
        public string name { get; set; } 
        public string sex { get; set; }
        public string tel { get; set; }

DAL.SqlHelper

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Yoodor.DAL
{
    public class SqlHelper
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public static string connectionString = ConfigurationManager.ConnectionStrings["Supermarket_DB"].ConnectionString;
        // Hashtable to store cached parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
        #region//ExecteNonQuery方法
        /// <summary>
        ///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
        /// 使用参数数组形式提供参数列表 
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                //通过PrePareCommand方法将参数逐个加入到SqlCommand的参数集合中
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                //清空SqlCommand中的参数列表
                cmd.Parameters.Clear();
                return val;
            }
        }
        /// <summary>
        ///执行一个不需要返回值的SqlCommand命令,通过指定专用的连接字符串。
        /// 使用参数数组形式提供参数列表 
        /// </summary>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecteNonQuery(connectionString, cmdType, cmdText, commandParameters);
        }
        /// <summary>
        ///存储过程专用
        /// </summary>
        /// <param name="cmdText">存储过程的名字</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecteNonQueryProc(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecteNonQuery(CommandType.StoredProcedure, cmdText, commandParameters);
        }
        /// <summary>
        ///Sql语句专用
        /// </summary>
        /// <param name="cmdText">T_Sql语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
        public static int ExecteNonQueryText(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecteNonQuery(CommandType.Text, cmdText, commandParameters);
        }
        #endregion
        #region//GetTable方法
        /// <summary>
        /// 执行一条返回结果集的SqlCommand,通过一个已经存在的数据库连接
        /// 使用参数数组提供参数
        /// </summary>
        /// <param name="connecttionString">一个现有的数据库连接</param>
        /// <param name="cmdTye">SqlCommand命令类型</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
        public static DataTableCollection GetTable(string connecttionString, CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            DataSet ds = new DataSet();
            using (SqlConnection conn = new SqlConnection(connecttionString))
            {
                PrepareCommand(cmd, conn, null, cmdTye, cmdText, commandParameters);
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = cmd;
                adapter.Fill(ds);
            }
            DataTableCollection table = ds.Tables;
            return table;
        }
        /// <summary>
        /// 执行一条返回结果集的SqlCommand,通过一个已经存在的数据库连接
        /// 使用参数数组提供参数
        /// </summary>
        /// <param name="cmdTye">SqlCommand命令类型</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
        public static DataTableCollection GetTable(CommandType cmdTye, string cmdText, SqlParameter[] commandParameters)
        {
            return GetTable(cmdTye, cmdText, commandParameters);
        }

        /// <summary>
        /// 存储过程专用
        /// </summary>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
        public static DataTableCollection GetTableProc(string cmdText, SqlParameter[] commandParameters)
        {
            return GetTable(CommandType.StoredProcedure, cmdText, commandParameters);
        }
        /// <summary>
        /// Sql语句专用
        /// </summary>
        /// <param name="cmdText"> T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个表集合(DataTableCollection)表示查询得到的数据集</returns>
        public static DataTableCollection GetTableText(string cmdText, SqlParameter[] commandParameters)
        {
            return GetTable(CommandType.Text, cmdText, commandParameters);
        }
        #endregion

        /// <summary>
        /// 为执行命令准备参数
        /// </summary>
        /// <param name="cmd">SqlCommand 命令</param>
        /// <param name="conn">已经存在的数据库连接</param>
        /// <param name="trans">数据库事物处理</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">Command text,T-SQL语句 例如 Select * from Products</param>
        /// <param name="cmdParms">返回带参数的命令</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>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static SqlDataReader ExecuteReader( 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);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch (Exception ex)
            {
                conn.Close();
                throw new Exception(ex.Message);
            }
        }
        #region//ExecuteDataSet方法
        /// <summary>
        /// 执行指定事务的命令,返回DataSet.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
        /// </remarks>
        /// <param name="transaction">事务</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名或T-SQL语句</param>
        /// <returns>返回一个包含结果集的DataSet</returns>
        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteDataSet(connectionString, commandType, commandText, (SqlParameter[])null);
        }
        /// <summary>
        /// return a dataset
        /// </summary>
        /// <param name="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>return a dataset</returns>
        public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataAdapter da = new SqlDataAdapter();
                DataSet ds = new DataSet();
                da.SelectCommand = cmd;
                da.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                //conn.Close(); //改动2013.7.42 16:32
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
        }

        /// <summary>
        /// 返回一个DataSet
        /// </summary>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>return a dataset</returns>
        public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteDataSet(connectionString, cmdType, cmdText, commandParameters);
        }
        /// <summary>
        /// 返回一个DataSet
        /// </summary>
        /// <param name="cmdText">存储过程的名字</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>return a dataset</returns>
        public static DataSet ExecuteDataSetProducts(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteDataSet(connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
        }
        /// <summary>
        /// 返回一个DataSet
        /// </summary>
        /// <param name="cmdText">T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>return a dataset</returns>
        public static DataSet ExecuteDataSetText(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteDataSet(connectionString, CommandType.Text, cmdText, commandParameters);
        }

        public static DataView ExecuteDataSet(string connectionString, string sortExpression, string direction, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataAdapter da = new SqlDataAdapter();
                DataSet ds = new DataSet();
                da.SelectCommand = cmd;
                da.Fill(ds);
                DataView dv = ds.Tables[0].DefaultView;
                dv.Sort = sortExpression + " " + direction;
                return dv;
            }
            catch (Exception ex)
            {
                //conn.Close(); //改动2013.7.42 16:32
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
        }
        #endregion

        #region // ExecuteScalar方法

        /// <summary>
        /// 返回第一行的第一列
        /// </summary>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个对象</returns>
        public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteScalar(SqlHelper.connectionString, cmdType, cmdText, commandParameters);
        }
        /// <summary>
        /// 返回第一行的第一列存储过程专用
        /// </summary>
        /// <param name="cmdText">存储过程的名字</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个对象</returns>
        public static object ExecuteScalarProducts(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteScalar(SqlHelper.connectionString, CommandType.StoredProcedure, cmdText, commandParameters);
        }
        /// <summary>
        /// 返回第一行的第一列Sql语句专用
        /// </summary>
        /// <param name="cmdText">者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param>
        /// <returns>返回一个对象</returns>
        public static object ExecuteScalarText(string cmdText, params SqlParameter[] commandParameters)
        {
            return ExecuteScalar(SqlHelper.connectionString, CommandType.Text, cmdText, commandParameters);
        }
        /// <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">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</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);
                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="connectionString">一个有效的数据库连接字符串</param>
        /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
        /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param>
        /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</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);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }
        #endregion

        /// <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>
        /// 检查是否存在
        /// </summary>
        /// <param name="strSql">Sql语句</param>
        /// <returns>bool结果</returns>
        public static bool Exists(string strSql)
        {
            int cmdresult = Convert.ToInt32(ExecuteScalar(connectionString, CommandType.Text, strSql, null));
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 检查是否存在
        /// </summary>
        /// <param name="strSql">Sql语句</param>
        /// <param name="cmdParms">参数</param>
        /// <returns>bool结果</returns>
        public static bool Exists(string strSql, params SqlParameter[] cmdParms)
        {
            int cmdresult = Convert.ToInt32(ExecuteScalar(connectionString, CommandType.Text, strSql, cmdParms));
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #region ExecuteDataTable方法
        public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText)
        {
            DataSet ds = ExecuteDataset(connectionString, commandType, commandText);
            if (ds == null || ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 1)
            {
                return null;
            }
            else
            {
                return ds.Tables[0];
            }
        }
        public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            DataSet ds = ExecuteDataSet(connectionString, commandType, commandText, commandParameters);
            if (ds == null || ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 1)
            {
                return null;
            }
            else
            {
                return ds.Tables[0];
            }
        }
        #endregion
        #region ExecuteDataRow 方法
        public static DataRow ExecuteDataRow(string connectionString, CommandType commandType, string commandText)
        {
            DataTable dt = ExecuteDataTable(connectionString, commandType, commandText);
            if (dt == null)
            {
                return null;
            }
            else
            {
                return dt.Rows[0];
            }
        }
        public static DataRow ExecuteDataRow(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            DataTable dt = ExecuteDataTable(connectionString, commandType, commandText, commandParameters);
            if (dt == null)
            {
                return null;
            }
            else
            {
                return dt.Rows[0];
            }
        }
        #endregion
    }
}

 

基于Jquery+Ajax+Json+存储过程 高效分页

标签:str   tab   param   focus   font   isnull   检查   exce   nbsp   

原文地址:https://www.cnblogs.com/njy888888/p/8488247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!