利用SQL語句實現分頁

1.概述

在網頁中若是顯示的數據太多就會佔據過多的頁面,並且顯示速度也會很慢。爲了控制每次在頁面上顯示數據的數量,就能夠利用分頁來顯示數據。html

 

2.技術要點

在SQL Server中要實現SQL分頁,須要使用子查詢來獲取上一頁的數據進行對比,進而獲取最新的數據。使用子查詢獲取分頁數據的語法格式以下:java

"SELECT TOP [pageSize] * FROM [table] WHERE id NOT IN(

                     SELECT TOP [preNum] id FROM [table] ORDER BY ID DESC) ORDER BY ID DESC";

 

 

a. pageSize:數據分頁的分頁大小。sql

b. preNum:上一頁數據查詢的起始範圍。數據庫

c. table:數據表名稱。jsp

例如要從數據庫的第10條數據開始查詢5條數據,編寫的 SQL查詢語句以下:sqlserver

"SELECT TOP 5 * FROM tb_SQLServerFenye WHERE id NOT IN(

                         SELECT TOP 10 id FROM tb_SQLServerFenye ORDER BY ID DESC) ORDER BY ID DESC";

 

 

在JDBCDao數據庫操做類的getPageArgs()方法中就使用getProducts()方法中就使用了該語法獲取指定頁碼的分頁數據,關鍵代碼以下:url

// 定義查詢數據庫的SQL語句

String sql = "SELECT TOP " + pageSize + " * FROM tb_SQLServerFenye" +

" WHERE id NOT IN(SELECT TOP " + (page - 1) * pageSize + " id FROM" +

" tb_SQLServerFenye ORDER BY ID DESC) ORDER BY ID DESC";

stmt = conn.createStatement();

rs = stmt.executeQuery(sql); // 執行SQL並獲取查詢結果集

 

3.實現過程

(1)建立操做數據庫類UserDao。經過構造方法UserDao()加載數據庫驅動,定義Connection()方法建立與數據庫的鏈接,定義selectStatic()方法執行查詢操做,定義closeConnection()方法關閉數據庫。其關鍵代碼以下:spa

 

public class UserDao {
      String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db_database04";     //url,數據庫
      String username="sa";                                                     //用戶名
      String password="";                                                       //密碼
         private Connection con = null;
         private Statement stmt = null;
         private ResultSet rs = null;
         public UserDao() {                                                          //經過構造方法加載數據庫驅動
        try {
                  Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            } catch (Exception ex) {
               System.out.println("數據庫加載失敗");
            }    
         }
         public boolean Connection() {                                             //建立數據庫鏈接
        try {
                 con = DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                 System.out.println(e.getMessage());
               System.out.println("creatConnectionError!");
            }
            return true;
         }
    
         public ResultSet selectStatic(String sql) throws SQLException {  //對數據庫的查詢操做
      ResultSet rs=null;
            if (con == null) {
                 Connection();
            }
           try {
                  stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            rs = stmt.executeQuery(sql);
     } catch (SQLException e) {
        e.printStackTrace();
     }
        return rs;
         }
         public void closeConnection() {                                         //關閉數據庫的操做
        if (con != null && stmt != null && rs != null) {
                 try {
                       rs.close();
                          stmt.close();
                          con.close();
              } catch (SQLException e) {
                       e.printStackTrace();
                          System.out.println("Failed to close connection!");
              } finally {
                       con = null;
                 }
            }
         }
}

(2)建立index.jsp頁面。首先經過JavaBean標籤調用數據可靠操做類UserDao,並定義在分頁輸出數據中使用的參數;code

<%@page contentType="text/html" pageEncoding="GBK" import="java.sql.*,java.util.*,java.lang.*"%>
<jsp:useBean id="selectall" scope="page" class="com.pkh.dao.UserDao"></jsp:useBean>
<%!
      int CountPage = 0;
      int CurrPage = 1;
      int PageSize = 5;
      int CountRow = 0; 
%>

而後,設置接收數據的參數,當第一次顯示頁面參數爲空時,設爲1。根據當前頁面的參數獲取到顯示的數據集。代碼以下:server

<%
      String StrPage = request.getParameter("Page");
      if (StrPage == null) {                                  //判斷當頁面的值爲空時
            CurrPage = 1;                               //賦值爲1
      } else {
            CurrPage = Integer.parseInt(StrPage);           //若是不爲空則獲取該值
      }
      String SQL = "Select * From tb_ClassList";          //定義查詢語句
      ResultSet Rs = selectall.selectStatic(SQL);           //執行查詢語句
      Rs.last();                                            //獲取查詢結果集
      int i = 0;                                             //定義數字變量
      CountRow = Rs.getRow();                          //獲取查詢結果集的行數
      CountPage = (CountRow / PageSize);                  //計算將數據分紅幾頁
      if (CountRow % PageSize > 0)                    //判斷若是頁數大於0
            CountPage++;                               //則增長該值
      Integer n = (CurrPage - 1) * 5 + 1;                            //定義變量上一頁的結束值
      SQL = "select top 5 * from tb_ClassList where CID>=" + "("
                                                        + "Select Max(CID) From (Select top " + n.toString()
                                                        + " * From tb_ClassList) as Class" + ")";
      Rs = selectall.selectStatic(SQL);                  //執行查詢語句
      while (Rs.next()) {                              //循環輸出查詢結果
%>
<tr>
      <td nowrap><span class="style3"><%=Rs.getString("CID")%></span></td>
      <td nowrap><span class="style3"><%=Rs.getString("CName")%></span></td>
      <td nowrap><span class="style3"><%=Rs.getString("CStartDate")%></span></td>
</tr>
<%
      }
      selectall.closeConnection();                         //關閉數據庫
%>

設置下一頁、上一頁和最後一頁超級連接,連接到index.jsp頁面,指定Page做爲欄目標識,將頁數做爲參數值,代碼以下:

<tr>
      <td width="251">
            [<%=CurrPage%>/<%=CountPage%>] 每頁5條 共<%=CountRow%>條記錄<%=(CurrPage - 1) * 5 + 1%>
      </td>
      <td width="260"><div align="right">
<% if (CurrPage > 1) {   %>
      <a href="index.jsp?Page=<%=CurrPage - 1%>">上一頁</a>
<% }    %>
<% if (CurrPage < CountPage) { %>
      <a href="index.jsp?Page=<%=CurrPage + 1%>">下一頁</a>
<% }    %>
      <a href="index.jsp?Page=<%=CountPage%>">最後一頁</a></div>
      </td>
</tr>
相關文章
相關標籤/搜索