明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

asp.net(C#)海量數(shù)據(jù)表高效率分頁(yè)算法

[摘要]首先創(chuàng)建一張表(要求ID自動(dòng)編號(hào)):create table redheadedfile(id int identity(1,1),filenames nvarchar(20),senduser nvarchar(20),primary key(id))然后我們寫入50萬(wàn)條記錄:declare @...
 

首先創(chuàng)建一張表(要求ID自動(dòng)編號(hào)):
create table redheadedfile(
id int identity(1,1),
filenames nvarchar(20),
senduser nvarchar(20),
primary key(id)
)
然后我們寫入50萬(wàn)條記錄:
declare @i int
set @i=1
while @i<=500000
begin
    insert into redheadedfile(filenames,senduser) values('我的分頁(yè)算法','陸俊銘')
    set @i=@i+1
end
GO
用Microsoft Visual Studio .NET 2003創(chuàng)建一張WebForm網(wǎng)頁(yè)(本人起名webform8.aspx)
前臺(tái)代碼片段如下(webform8.aspx):
<%@ Page language="c#" Codebehind="WebForm8.aspx.cs" AutoEventWireup="false" Inherits="WebApplication6.WebForm8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm8</title>
  <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <asp:datalist id="datalist1" AlternatingItemStyle-BackColor="#f3f3f3" Width="100%" CellSpacing="0"
    CellPadding="0" Runat="server">
    <ItemTemplate>
     <table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
       <td width="30%"

align="center"><%#DataBinder.Eval(Container.DataItem,"filenames")%></td>
       <td width="30%"

align="center"><%#DataBinder.Eval(Container.DataItem,"senduser")%></td>
       <td width="30%"

align="center"><%#DataBinder.Eval(Container.DataItem,"id")%></td>
      </tr>
     </table>
    </ItemTemplate>
   </asp:datalist>
   <div align="center">共<asp:label id="LPageCount" Runat="server" ForeColor="#ff0000"></asp:label>頁(yè)/共

<asp:label id="LRecordCount" Runat="server" ForeColor="#ff0000"></asp:label>記錄
    <asp:linkbutton id="Fistpage" Runat="server"

CommandName="0">首頁(yè)</asp:linkbutton>&nbsp;&nbsp;&nbsp;&nbsp;<asp:linkbutton id="Prevpage" Runat="server" CommandName="prev">

上一頁(yè)</asp:linkbutton>&nbsp;&nbsp;&nbsp;&nbsp;<asp:linkbutton id="Nextpage" Runat="server"

CommandName="next">下一頁(yè)</asp:linkbutton>&nbsp;&nbsp;&nbsp;&nbsp;<asp:linkbutton id="Lastpage" Runat="server"

CommandName="last">尾頁(yè)</asp:linkbutton>&nbsp;&nbsp;&nbsp;&nbsp;當(dāng)前第<asp:label id="LCurrentPage" Runat="server"

ForeColor="#ff0000"></asp:label>頁(yè)&nbsp;&nbsp;&nbsp;&nbsp;跳頁(yè)<asp:TextBox ID="gotoPage" Runat="server" Width="30px"

MaxLength="5" AutoPostBack="True"></asp:TextBox></div>
  </form>
 </body>
</HTML>
后臺(tái)代碼片段如下(webform8.aspx.cs)
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;

namespace WebApplication6
{
 /// <summary>
 /// WebForm8 的摘要說(shuō)明。
 /// </summary>
 public class WebForm8 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.LinkButton Fistpage;
  protected System.Web.UI.WebControls.LinkButton Prevpage;
  protected System.Web.UI.WebControls.LinkButton Nextpage;
  protected System.Web.UI.WebControls.LinkButton Lastpage;
  protected System.Web.UI.WebControls.DataList datalist1;
  protected System.Web.UI.WebControls.DropDownList mydroplist;
  protected System.Web.UI.WebControls.Label LPageCount;
  protected System.Web.UI.WebControls.Label LRecordCount;
  protected System.Web.UI.WebControls.Label LCurrentPage;
  protected System.Web.UI.WebControls.TextBox gotoPage;
  const int PageSize=20;//定義每頁(yè)顯示記錄
  int PageCount,RecCount,CurrentPage,Pages,JumpPage;//定義幾個(gè)保存分頁(yè)參數(shù)變量
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(!IsPostBack)
   {
    RecCount = Calc();//通過(guò)Calc()函數(shù)獲取總記錄數(shù)
    PageCount = RecCount/PageSize + OverPage();//計(jì)算總頁(yè)數(shù)(加上OverPage()函數(shù)防止有余數(shù)造成顯示

數(shù)據(jù)不完整)

    ViewState["PageCounts"] = RecCount/PageSize -

ModPage();//保存總頁(yè)參數(shù)到ViewState(減去ModPage()函數(shù)防止SQL語(yǔ)句執(zhí)行時(shí)溢出查詢范圍,可以用存儲(chǔ)過(guò)程分頁(yè)算法來(lái)理解這句)
    ViewState["PageIndex"] = 0;//保存一個(gè)為0的頁(yè)面索引值到ViewState
    ViewState["JumpPages"] = PageCount;//保存PageCount到ViewState,跳頁(yè)時(shí)判斷用戶輸入數(shù)是否超出頁(yè)

碼范圍
    //顯示LPageCount、LRecordCount的狀態(tài)
    LPageCount.Text = PageCount.ToString();
    LRecordCount.Text = RecCount.ToString();
    //判斷跳頁(yè)文本框失效
    if(RecCount <= 20)
     gotoPage.Enabled = false;
    TDataBind();//調(diào)用數(shù)據(jù)綁定函數(shù)TDataBind()進(jìn)行數(shù)據(jù)綁定運(yùn)算
   }
  }
        //計(jì)算余頁(yè)
  public int OverPage()
  {
   int pages = 0;
   if(RecCount%PageSize != 0)
    pages = 1;
   else
    pages = 0;
   return pages;
  }
        //計(jì)算余頁(yè),防止SQL語(yǔ)句執(zhí)行時(shí)溢出查詢范圍
  public int ModPage()
  {
   int pages = 0;
   if(RecCount%PageSize == 0 && RecCount != 0)
    pages = 1;
   else
    pages = 0;
   return pages;
  }
        /*
   *計(jì)算總記錄的靜態(tài)函數(shù)
   *本人在這里使用靜態(tài)函數(shù)的理由是:如果引用的是靜態(tài)數(shù)據(jù)或靜態(tài)函數(shù),連接器會(huì)優(yōu)化生成代碼,去掉動(dòng)態(tài)重定位項(xiàng)(對(duì)

海量數(shù)據(jù)表分頁(yè)效果更明顯)。
   *希望大家給予意見(jiàn)、如有不正確的地方望指正。
  */
  public static int Calc()
  {
   int RecordCount = 0;
   SqlCommand MyCmd = new SqlCommand("select count(*) as co from redheadedfile",MyCon());
   SqlDataReader dr = MyCmd.ExecuteReader();
   if(dr.Read())
    RecordCount = Int32.Parse(dr["co"].ToString());
   MyCmd.Connection.Close();
   return RecordCount;
  }
        //數(shù)據(jù)庫(kù)連接語(yǔ)句(從Web.Config中獲。
  public static SqlConnection MyCon()
  {
   SqlConnection MyConnection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
   MyConnection.Open();
   return MyConnection;
  }
        //對(duì)四個(gè)按鈕(首頁(yè)、上一頁(yè)、下一頁(yè)、尾頁(yè))返回的CommandName值進(jìn)行操作
  private void Page_OnClick(object sender, CommandEventArgs e)
  {
   CurrentPage = (int)ViewState["PageIndex"];//從ViewState中讀取頁(yè)碼值保存到CurrentPage變量中進(jìn)行參數(shù)運(yùn)


            Pages = (int)ViewState["PageCounts"];//從ViewState中讀取總頁(yè)參數(shù)運(yùn)算

   string cmd = e.CommandName;
   switch(cmd)//篩選CommandName
   {
    case "next":
     CurrentPage++;
     break;
    case "prev":
     CurrentPage--;
     break;
    case "last":
     CurrentPage = Pages;
     break;
    default:
     CurrentPage = 0;
     break;
   }
   ViewState["PageIndex"] = CurrentPage;//將運(yùn)算后的CurrentPage變量再次保存至ViewState
   TDataBind();//調(diào)用數(shù)據(jù)綁定函數(shù)TDataBind()
  }

  private void TDataBind()
  {
   CurrentPage = (int)ViewState["PageIndex"];//從ViewState中讀取頁(yè)碼值保存到CurrentPage變量中進(jìn)行按鈕失

效運(yùn)算
   Pages = (int)ViewState["PageCounts"];//從ViewState中讀取總頁(yè)參數(shù)進(jìn)行按鈕失效運(yùn)算
   //判斷四個(gè)按鈕(首頁(yè)、上一頁(yè)、下一頁(yè)、尾頁(yè))狀態(tài)
   if (CurrentPage + 1 > 1)
   {
    Fistpage.Enabled = true;
    Prevpage.Enabled = true;
   }
   else
   {
    Fistpage.Enabled = false;
    Prevpage.Enabled = false;
   }
   if (CurrentPage == Pages)
   {
    Nextpage.Enabled = false;
    Lastpage.Enabled = false;
   }
   else
   {
    Nextpage.Enabled = true;
    Lastpage.Enabled = true;
   }
            //數(shù)據(jù)綁定到DataList控件
   DataSet ds = new DataSet();
   //核心SQL語(yǔ)句,進(jìn)行查詢運(yùn)算(決定了分頁(yè)的效率:))
   SqlDataAdapter MyAdapter = new SqlDataAdapter("Select Top "+PageSize+" * from redheadedfile where id

not in(select top "+PageSize*CurrentPage+" id from redheadedfile order by id asc) order by id asc",MyCon());
   MyAdapter.Fill(ds,"news");
   datalist1.DataSource = ds.Tables["news"].DefaultView;
   datalist1.DataBind();
   //顯示Label控件LCurrentPaget和文本框控件gotoPage狀態(tài)
   LCurrentPage.Text = (CurrentPage+1).ToString();
   gotoPage.Text = (CurrentPage+1).ToString();
   //釋放SqlDataAdapter
   MyAdapter.Dispose();
  }

  #region Web 窗體設(shè)計(jì)器生成的代碼
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 該調(diào)用是 ASP.NET Web 窗體設(shè)計(jì)器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 設(shè)計(jì)器支持所需的方法 - 不要使用代碼編輯器修改
  /// 此方法的內(nèi)容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Fistpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
   this.Prevpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
   this.Nextpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
   this.Lastpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
   this.gotoPage.TextChanged += new System.EventHandler(this.gotoPage_TextChanged);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion
        //跳頁(yè)代碼
  private void gotoPage_TextChanged(object sender, System.EventArgs e)
  {
   try
   {
    JumpPage = (int)ViewState["JumpPages"];//從ViewState中讀取可用頁(yè)數(shù)值保存到JumpPage變量中
    //判斷用戶輸入值是否超過(guò)可用頁(yè)數(shù)范圍值
    if(Int32.Parse(gotoPage.Text) > JumpPage Int32.Parse(gotoPage.Text) <= 0)
     

Response.Write("<script>alert('頁(yè)碼范圍越界!');location.href='WebForm8.aspx'</script>");
    else
    {
     int InputPage = Int32.Parse(gotoPage.Text.ToString()) - 1;//轉(zhuǎn)換用戶輸入值保存在int型

InputPage變量中
     ViewState["PageIndex"] = InputPage;//寫入InputPage值到ViewState["PageIndex"]中
     TDataBind();//調(diào)用數(shù)據(jù)綁定函數(shù)TDataBind()再次進(jìn)行數(shù)據(jù)綁定運(yùn)算
    }
   }
      //捕獲由用戶輸入不正確數(shù)據(jù)類型時(shí)造成的異常
   catch(Exception exp)
   {
    Response.Write("<script>alert('"+exp.Message+"');location.href='WebForm8.aspx'</script>");
   }
  }
 }
}