c#學習之-c#通過sql存儲過程實現分頁

c#學習之-c#通過sql存儲過程實現分頁

分頁的重要性不言而喻,本文將相信的講解c#通過sql進行分頁的實現(三層)

數據庫表如下

現在編寫sql分頁通用存儲過程

if exists (select 1 
		   from sysobjects 
		   where [name]='proc_CommonPage' 
		   and [type]='p')
   drop proc proc_CommonPage--檢查是否存在該存儲過程 如果存在刪除
go
create proc proc_CommonPage--創建存儲過程
( @pageSize int,--分頁大小(每一頁多少)
  @pageIndex int,--分頁索引(頁數)
  @tablename varchar(50),--表名
  @prikey varchar(20),--查詢關鍵字(以什麼排序)
  @condtional varchar(2000),--查詢條件
  @sort varchar(4),--排序
  @pageCount int out --總頁數
  
)
as
--構建查詢的sql語句
declare @sql nvarchar(1000);--查詢的sql
declare @recordCount int,--數據總數
        @startIndex int,--分頁的啓示行  
	@endIndex int--分頁的結束行

set @sql='select @recordCount=count(*) from '+@tablename+' where 1=1 ';
if	@condtional is not null and @condtional<> N''--查詢條件不爲空 也不爲空格
begin
set @sql=@sql+@condtional
end
--print @sql
exec sp_executesql @sql,N'@recordCount int out',@recordCount out;--執行系統sp_executesql存儲過程
print @recordCount
 --計算最大的分頁數--
 set @pageCount = CEILING(@recordcount*1.0/@pagesize);--最大的分頁數 進一法取值
 if @pageindex > @pageCount   --如果分頁的索引大於最大的索引
 begin
    set @pageindex = @pageCount;
 end
 --構建分頁的查詢的起始行和結束行
 set @startIndex = (@pageindex-1)*@pagesize +1;--計算起始行
 set @endIndex = @pageindex *@pagesize
 --構建分頁的sql
 set @sql =''
  print @pagecount
 set @sql = 'Select row_number()  over (order by '+@prikey+ ' ' +@sort+') as rowid,*  from '+@tablename+' where 1=1';
 if @condtional is not null and @condtional <> N''   --如果查詢條件不爲空
 begin
    set @sql = @sql+ @condtional;
 end
 set @sql = 'Select * From ('+@sql+') as tc where tc.rowid between '+convert(varchar(5),@startIndex)+' and '+convert(varchar(5),@endIndex)+'';
 exec (@sql)

 go

在這個存儲過程中有2個地方需要注意

第一   sp_executesql

執行可以多次重複使用或動態生成的 Transact-SQL 語句或批處理。Transact-SQL 語句或批處理可以包含嵌入參數。

(個人理解)主要可以執行一個sql語句 並且可以傳出參數 用來作爲下一條語句的條件 它的參數必須是Unicode字符格式

第二   row_number()

select row_number() over (order by empid asc) as rowid 像表中插入一列帶有順序的id

UI層

EmployedBll eb = new EmployedBll();        int pageSize = 6;        int pageIndex = 1;        int pageCount = 0;        string pageConditiona = "";

 List<TbEmployed> list = eb.GetListByPage(pageSize, pageIndex, pageConditiona, pageSort, out pageCount);
            this.gridControl1.DataSource = list;
 

BLL層

        private string pageSort = "asc";


 

public List<TbEmployed> GetListByPage(int PageSize, int pageIndex, string seletstr,string pageSort, out int pageCount)
        {
            return ed.GetListByPage(PageSize, pageIndex, seletstr,pageSort, out pageCount);
        }


 

DAL層

 

 public List<TbEmployed> GetListByPage(int pageSize, int pageIndex, string seletcondtional,string pageSort,out int pagecount)
        {

                #region MyRegion
                SqlParameter parIndex = new SqlParameter("@pageIndex", SqlDbType.Int);
                parIndex.Value = pageIndex;
                SqlParameter parSize = new SqlParameter("@PageSize", SqlDbType.Int);
                parSize.Value = pageSize;
                SqlParameter parTname = new SqlParameter("@tablename", SqlDbType.VarChar);
                parTname.Value = "tb_Employed";
                SqlParameter parPrikey = new SqlParameter("@prikey", SqlDbType.VarChar);
                parPrikey.Value = "empid";
                SqlParameter parSort = new SqlParameter("@pageSort", SqlDbType.VarChar);
                parSort.Value = pageSort;SqlParameter parCondtional = new SqlParameter("@condtional", SqlDbType.VarChar);
                parCondtional.Value =seletcondtional;
                SqlParameter parCount = new SqlParameter("@pagecount", SqlDbType.Int);
                parCount.Direction = ParameterDirection.Output;//傳出參數      Direction    
                SqlParameter[] pars = { parSize, parIndex, parTname, parPrikey, parCondtional,parSort, parCount };
                string sql = " exec proc_CommonPage @pageSize,@pageIndex,@tablename,@prikey,@condtional,@pageSort,
		@pagecount out";
                DataTable dt = _sqlhelper.GetDataSet(sql, pars).Tables[0];
            
                //  DataTable dt = _sqlhelper.GetDataTable(sql, pars);
                pagecount = (int)parCount.Value;//把結構賦值給傳出參數Pagecount   
                List<TbEmployed> list = GetListModel(dt); 
                #endregion

                #region MyRegion
            //string tablename = "tb_Employed";
            //string prikey = "empid";
            //string condtional = "";
            //DataTable dt =
            //    _sqlhelper.GetDataSet(
            //        @"exec proc_CommonPage @pageIndex,@PageSize,@tablename,@prikey,@condtional,@pageCount out",
            //        new SqlParameter("@pageIndex", pageIndex),
            //        new SqlParameter("@PageSize", PageSize),
            //        new SqlParameter("@tablename", tablename),
            //        new SqlParameter("@prikey", prikey),
            //        new SqlParameter("@condtional", condtional),
            //        new SqlParameter("@pageCount", pageCount)).Tables[0];
            //pageCount = (int)parCount.Value;//把結構賦值給傳出參數Pagecount
            //List<TbEmployed> list = GetListModel(dt);  
            #endregion
                return list;
<pre class="csharp" name="code"> private List<TbEmployed> GetListModel(DataTable dt)
        {
            List<TbEmployed> list = new List<TbEmployed>();
            foreach (DataRow dr in  dt.Rows)
            {
                TbEmployed te = new TbEmployed();
                te.empid = (int) dr["empid"];
                te.empname = dr["empname"].ToString();
                te.roleid = (int) dr["roleid"];
                te.empsex = dr["empsex"].ToString();
                te.empage = (int)dr["empage"];
                te.emplogin = dr["emplogin"].ToString();
                te.empwd = dr["empwd"].ToString();            
                list.Add(te);
            }
            return list;
        }


AbstractSqlHelper

  public SqlCommand GetCommand(string sql, params SqlParameter[] pars)
        {
            GetConnection();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;         
            if (pars != null)
            {
                cmd.Parameters.AddRange(pars);
            }
            return cmd;
        
        }
 public void GetConnection()
        {    //private static string conStr = ConfigurationManager.ConnectionStrings["sqlstr"].ConnectionString;
             string strCon = ConfigurationManager.ConnectionStrings["sqlstr"].ConnectionString;
            conn = new SqlConnection(strCon);
            conn.Open();
            if (conn.State!=ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }


 

 public SqlCommand GetCommand(string sql, params SqlParameter[] pars)
        {
            GetConnection();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;         
            if (pars != null)
            {
                cmd.Parameters.AddRange(pars);
            }
            return cmd;
        
        }



 

SqlHelper

 public override DataSet GetDataSet(string sql, params SqlParameter[] parameters)
        {
            SqlCommand cmd = GetCommand(sql, parameters);          
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet dataset = new DataSet();
            sda.Fill(dataset);
            return dataset;  
        }

 

以上是實習分頁的全部代碼

model省略了的

表名 關鍵字也可以通過參數傳入

代碼間調用就是普通的調用 數據連接的打開在抽象類中

連接字符串在配置文件中

以winfrom 爲教材

希望大家批評指教

 


 


 

 

 

 

發佈了38 篇原創文章 · 獲贊 13 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章