sql语句 实现分页

sql语句 实现分页

/*

分页思想:比如你要每页获取10条记录,当你显示第5页的记录时,
也就是选取第40条至50条的记录.首先应该从所有的记录集中选取
50条记录,同时进行倒序,再从中选10条,就完成工作了。

下面是一个具体的例子,从Northwind的Orders表中选取OrderID大于@OrderID的记录集,
分10条每页显示.
*/

--有查询条件的分页存储过程


create procedure dbo.Orders_GetByPaging

@OrderID int,   --条件
@PageSize int,  --每页的记录数量,比如10条,传参数时就是10
@CurrentPage int  --第N页,比如第5页,传参数就是5
as
declare @PageCount int --可分页的数量
declare @RowsCount int  --符合查询条伯的记录行总数
declare @LastRows int   --整除后余下来的记录数
declare @SelectRowsCount int --要选择的行数

   set @RowsCount=(select count(*) from dbo.Orders where OrderID>@OrderID)
   set @PageCount=@RowsCount/@PageSize   --看下能分多少页
   set @LastRows=@RowsCount%@PageSize
   set @SelectRowsCount=@PageSize   --给要选取的行数赋值,如参数是10,就是每页10条记录         
   if(@LastRows>0)--当整除后还剩的记录数,比如总有95条记录符合,那就可以分10页,最后一页是5条记录
   begin
        set @PageCount=@PageCount+1  --如果不能整除时要多加一页
        if(@CurrentPage>=@PageCount)  --如果选择的是最后一页时
           set  @SelectRowsCount=@LastRows  --比如95条记录,第10页只能是5条记录
   end
declare @SelectStr varchar(5000)
set @SelectStr='select top '+Convert(nvarchar(10),@SelectRowsCount)+' 
* from

(select top '+Convert(nvarchar(10),(@CurrentPage)*@PageSize)+' * from 
(select * from dbo.Orders where OrderID>'+Convert(nvarchar(10),@OrderID)+') as t1 order by OrderID asc) as t2 order by OrderID desc'

execute(@SelectStr)

======================

在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>

猜你喜欢

转载自blog.csdn.net/qq_32444825/article/details/80376903