利用SQL语句实现分页

1.概述

在网页中如果显示的数据太多就会占据过多的页面,而且显示速度也会很慢。为了控制每次在页面上显示数据的数量,就可以利用分页来显示数据。

2.技术要点

在SQL Server中要实现SQL分页,需要使用子查询来获取上一页的数据进行对比,进而获取最新的数据。使用子查询获取分页数据的语法格式如下:

"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:数据分页的分页大小。

b. preNum:上一页数据查询的起始范围。

c. table:数据表名称。

例如要从数据库的第10条数据开始查询5条数据,编写的 SQL查询语句如下:

"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()方法中就使用了该语法获取指定页码的分页数据,关键代码如下:

// 定义查询数据库的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()方法关闭数据库。其关键代码如下:

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,并定义在分页输出数据中使用的参数;

<%@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。根据当前页面的参数获取到显示的数据集。代码如下:

<%
      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>
原文地址:https://www.cnblogs.com/zkn11199/p/5576536.html