C#数据分页实现

BaseDAO.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using Beyondbit.OADoc.Common;

namespace Beyondbit.OADoc.DAO {
    public class BaseDAO {
        protected SqlConnection connection = null;
        protected SqlCommand cmd = null;
        protected bool outerConnection = false;
        public BaseDAO() {
            if (connection == null)
                connection = new SqlConnection(Config.ConnectionString);
            cmd = new SqlCommand();
            cmd.Connection = connection;
        }

        public BaseDAO(SqlConnection conn) {
            if (conn != null) {
                connection = conn;
                outerConnection = true;
            } else {
                connection = new SqlConnection(Config.ConnectionString);
            }
            cmd = new SqlCommand();
            cmd.Connection = connection;
        }

        protected void OpenConnection() {
            if (!outerConnection)
                connection.Open();
        }

        protected void CloseConnection() {
            if (!outerConnection && connection.State != System.Data.ConnectionState.Closed)
                connection.Close();
        }

        public string GetUnitName(string unitCode) {
            this.cmd.CommandText = "SELECT ORG_NAME FROM BUA_ORGANIZATION WHERE ORG_CODE=@ORGCODE";
            this.cmd.Parameters.Clear();
            this.cmd.Parameters.Add(MakeInParameter("ORGCODE", unitCode));
            this.cmd.CommandType = CommandType.Text;
            string result = null;
            try {
                OpenConnection();
                result = (string)this.cmd.ExecuteScalar();
            } finally {
                CloseConnection();
            }
            return result;
        }

        protected DataTable Search(PageCondition pc) {
            //string wherePredication, string orderByColumns, string tableName, out int recordCount,
            //out int pageCount) {
            if (pc.CurrentPageIndex < 1) {
                pc.RecordCount = 0;
                pc.PageCount = 0;
                return null;
            }
            if (pc.PageSize < 1) {
                pc.RecordCount = 0;
                pc.PageCount = 0;
                return null;
            }

            StringBuilder buffer = new StringBuilder(800);
            string firstColumn = null;
            if (pc.SelectColumns.IndexOf(",") != -1)
                firstColumn = pc.SelectColumns.Split(",".ToCharArray())[0];
            else
                firstColumn = pc.SelectColumns;

            buffer.Append("SELECT COUNT(");
            buffer.Append(firstColumn);
            buffer.Append(") FROM ");
            buffer.Append(pc.TableName);
            buffer.Append(" ");
            if (!String.IsNullOrEmpty(pc.WherePredication)) {
                buffer.Append(" WHERE ");
                buffer.Append(pc.WherePredication);
            }
            
            buffer.Append(";"); //不加;要出错,共查询出两个结果

            buffer.Append(@"WITH t AS(
                SELECT ROW_NUMBER() OVER(ORDER BY ");
            buffer.Append(pc.OrderByColumns);
            buffer.Append(@") AS RowNumber, ");
            buffer.Append(pc.SelectColumns);
            buffer.Append(" FROM ");
            buffer.Append(pc.TableName);
            buffer.Append(" WHERE ");
            buffer.Append(pc.WherePredication);
            buffer.Append(")");
            buffer.Append(" SELECT * from t ");

            int startRowNum, endRowNum;
            startRowNum = (pc.CurrentPageIndex - 1) * pc.PageSize + 1;
            endRowNum = pc.CurrentPageIndex * pc.PageSize;

            buffer.Append(" WHERE RowNumber >= ");
            buffer.Append(startRowNum.ToString());
            buffer.Append(" AND RowNumber <=");
            buffer.Append(endRowNum.ToString());

            this.cmd.Parameters.Clear();
            this.cmd.CommandType = CommandType.Text;
            this.cmd.CommandText = buffer.ToString();
            DataSet ds = null;

            try {
                OpenConnection();

                SqlDataAdapter adapter = new SqlDataAdapter(this.cmd);
                ds = new DataSet();
                adapter.Fill(ds);
                pc.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            } finally {
                CloseConnection();
            }

            //计算总的页数
            if (pc.RecordCount <= pc.PageSize)
                pc.PageCount = 1;
            else {
                if (pc.RecordCount % pc.PageSize > 0)
                    pc.PageCount = pc.RecordCount / pc.PageSize + 1;
                else
                    pc.PageCount = pc.RecordCount / pc.PageSize;
            }

            if (pc.CurrentPageIndex > pc.PageCount)
                return null;

            return ds.Tables[1];
        }


        private SqlParameter makeParameter(string paramName, SqlDbType type, int size, ParameterDirection direction, object value) {
            SqlParameter p = new SqlParameter(paramName, value);
            p.SqlDbType = type;
            p.Direction = direction;
            if (size != -1)
                p.Size = size;
            return p;
        }

        private SqlParameter makeParameter(string paramName, int size, ParameterDirection direction, object value) {
            SqlParameter p = new SqlParameter(paramName, value);
            p.Direction = direction;
            if (size != -1)
                p.Size = size;
            return p;
        }

        protected SqlParameter MakeInParameter(string paramName, SqlDbType type, int size, object value) {
            return makeParameter(paramName, type, size, ParameterDirection.Input, value);
        }

        protected SqlParameter MakeInParameter(string paramName, SqlDbType type, object value) {
            return makeParameter(paramName, type, -1, ParameterDirection.Input, value);
        }

        protected SqlParameter MakeInParameter(string paramName, object value) {
            return makeParameter(paramName, -1, ParameterDirection.Input, value);
        }

        protected SqlParameter MakeOutParameter(string paramName, SqlDbType type, int size, object value) {
            return makeParameter(paramName, type, size, ParameterDirection.Output, value);
        }

        protected SqlParameter MakeOutParameter(string paramName, SqlDbType type, object value) {
            return makeParameter(paramName, type, -1, ParameterDirection.Output, value);
        }

        protected SqlParameter MakeOutParameter(string paramName, object value) {
            return makeParameter(paramName, -1, ParameterDirection.Output, value);
        }
    }
}

----------------------------------------------------------------------------------------------------
PageCondition.cs

//----------------------------------------------------------------
// Copyright (C) 2009 上海互联网软件有限公司
// 版权所有。
// All rights reserved.
//
// 文件名:PageCondition.cs
// 文件功能描述:分页条件实体类
//
//
// 创建标识:袁晓平2009-02-10
//
// 修改标识:
// 修改描述:
//----------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace Beyondbit.OADoc.Common
{

    /// <summary>
    /// 分页条件实体类
    /// </summary>
    public class PageCondition
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public PageCondition()
        {
            sendStatus = 2;    //已发送
            receiveStatus = 0;
        }

        /// <summary>
        /// 每页显示的记录数量
        /// </summary>
        private int pageSize;

        /// <summary>
        /// 每页显示的记录数量
        /// </summary>
        public int PageSize
        {
            get
            {
                return this.pageSize;
            }
            set
            {
                this.pageSize = value;
            }
        }

        /// <summary>
        /// 表示当前页的索引
        /// </summary>
        private int currentPageIndex;

        /// <summary>
        /// 表示当前页的索引
        /// </summary>
        public int CurrentPageIndex
        {
            get
            {
                return this.currentPageIndex;
            }
            set
            {
                this.currentPageIndex = value;
            }
        }

        /// <summary>
        /// 表示查询的记录数量
        /// </summary>
        private int recordCount;

        /// <summary>
        /// 表示查询的记录数量
        /// </summary>
        public int RecordCount
        {
            get
            {
                return this.recordCount;
            }
            set
            {
                this.recordCount = value;
            }
        }

        /// <summary>
        /// 表示查询的总页数
        /// </summary>
        private int pageCount;

        /// <summary>
        /// 表示查询的总页数
        /// </summary>
        public int PageCount
        {
            get
            {
                return this.pageCount;
            }
            set
            {
                this.pageCount = value;
            }
        }

        /// <summary>
        /// 选择的列,如Name,ID,Seq 表示选取姓名、ID、Seq列或者 * 表示选取所有列
        /// 如果有表的别名可如:a.Name,a.ID,b.DocumentID 形式
        /// </summary>
        private string selectColumns;

        /// <summary>
        /// 选择的列,如Name,ID,Seq 表示选取姓名、ID、Seq列或者 * 表示选取所有列
        /// 如果有表的别名可如:a.Name,a.ID,b.DocumentID 形式
        /// </summary>
        public string SelectColumns
        {
            get
            {
                return this.selectColumns;
            }
            set
            {
                this.selectColumns = value;
            }
        }

        /// <summary>
        /// Where子句
        /// </summary>
        private string wherePredication;

        /// <summary>
        /// Where子句
        /// </summary>
        public string WherePredication
        {
            get
            {
                return this.wherePredication;
            }
            set
            {
                this.wherePredication = value;
            }
        }

        /// <summary>
        /// OrderBy列名
        /// </summary>
        private string orderByColumns;

        /// <summary>
        /// OrderBy列名
        /// </summary>
        public string OrderByColumns
        {
            get
            {
                return this.orderByColumns;
            }
            set
            {
                this.orderByColumns = value;
            }
        }

        /// <summary>
        /// 查询的表名
        /// </summary>
        private string tableName;

        /// <summary>
        /// 查询的表名
        /// </summary>
        public string TableName
        {
            get
            {
                return this.tableName;
            }
            set
            {
                this.tableName = value;
            }
        }

        /// <summary>
        /// 是否倒排序
        /// </summary>
        private bool isDesc;

        /// <summary>
        /// 是否倒排序
        /// </summary>
        public bool IsDesc
        {
            get
            {
                return this.isDesc;
            }
            set
            {
                this.isDesc = value;
            }
        }        

        /// <summary>
        /// 发送状态
        /// </summary>
        private int sendStatus;

        /// <summary>
        /// 发送状态
        /// </summary>
        public int SendStatus
        {
            get
            {
                return this.sendStatus;
            }
            set
            {
                this.sendStatus = value;
                if (sendStatus > 0)
                    this.receiveStatus = 0;
            }
        }

        /// <summary>
        /// 接收状态
        /// </summary>
        private int receiveStatus;

        /// <summary>
        /// 接收状态
        /// </summary>
        public int ReceiveStatus
        {
            get
            {
                return this.receiveStatus;
            }
            set
            {
                this.receiveStatus = value;
                if (this.receiveStatus > 0)
                    this.sendStatus = 0;
            }
        }
    }
}
----------------------------------------------------------------------------------------
调用示例:
PageCondition p = new PageCondition();
p.PageSize = 20;
p.CurrentPageIndex = 2;
p.IsDesc = true;

p.TableName = "[DOCUMENT] A JOIN ReceiveUnit B ON B.DocumentID=A.ID";
//上面这样写可以支持多表连接查询,或者像下面这样写,只查一个表:
//p.TableName = "[DOCUMENT] A";
//选择的数据字段,或者用*表示所有字段
p.SelectColumns = "A.id,A.Documentid,A.title,A.NAME";
//自定义查询条件
p.WherePredication = "A.SENDERStatus=2";
//支持多字段排序
p.OrderByColumns = "A.NAME DESC,A.Title ASC";

DataTable result = Search(p);


你可能感兴趣的:(C#)