jdbc之分页查询

  分页查询作为一项十分重要的数据库查询技术,在很多web项目中都会要用到,当然移动开发中也是会涉及的。

一、分页查询的sql语句:

  ps:为了方便阐述,下面统一使用student表作为查询的表;colName表示student表中的某个字段名字。

  1、mysql

  select * from student (order by colName) limit m, n;

    参数解释  m:表示要查询记录的上一行的行号,比如要从第1条记录开始查则m取0;

           n:表示希望从m+1开始查询多少条记录;

   示例:

  studet表中的数据如下

  

  

  

  

  2、oracle

  select * from (select t.*,rownum rn from (select * from student) t where rownum<=m) where rn>=n;

  参数解释  rownum:是oracle系统为查询返回的行顺序分配的编号,详细介绍请参考该博文:http://www.cnblogs.com/zjrstar/archive/2006/08/31/491090.html

        m:查询的最大行号;

          n:查询的最小行号;

        这样查询的结果行数为:m-n+1

  示例:

  student表中的数据如下:

  

  

  3、sql server

  实现的sql语法有多种:

    ①利用ID大于多少

    select top 4 * from student where stuid>( select max(stuid) from ( select top 2 stuid from student order by stuid ) as t ) order by stuid;

    ②利用not in

    select top 4 * from student where stuid not in ( select top 2 stuid from student order by stuid) as t order by stuid;

    ③利用颠倒型top

    select * from ( select top 4 * from ( select top 6 * from student order by stuid )  as t order by t.stuid desc ) as t1 order by t1.stuid;

    ④使用ROW_NUMBER()函数

    select * from ( select *,row_number() over (order by stuid) as rank from student ) as t where t.rank between 3 and 6;

  由于没怎么用sql server,所以电脑上没装,这里就不给出查询示例了。

二、jdbc中如何实现动态分页

  1、四个重要参数

    pageNow  当前的页码

    pageCount 总页数

    pageSize  每页中显示多少条记录

    rowCount   表中记录的总行数

  2、根据rowCount和pageSize计算pageCount的小算法

    ①  if(rowCount % pageSize == 0) {

          pageCount = rowCount / pageSize;

       } else {

          pageCount = rowCount / pageSize + 1;

       }

    ②  pageCount = rowCount % pageSize == 0 ? rowCount / pageSize : rowCount / pageSize  + 1;

    ③  pageCount = (rowCount - 1) / pageSize + 1;

    原理是一样的,只是给出了三种形式,个人比较喜欢③。

  3、将pageSize和pageNow用在jdbc的sql语句中查询当前页的记录

    ⑴mysql

    select * from student (order by colName) limit (pageNow-1)*pageSize, pageSize;

    ⑵oracel

    select * from (select t.*,rownum rn from (select * from student) t where rownum<=pageNow*pageSize) where rn>=(pageNow-1)*pageSize+1;

    ⑶sql server

    select top pageSize * from student where stuid>( select max(stuid) from ( select top (pageNow-1)*pageSize stuid from student order by stuid ) as t ) order by stuid;

    sql server分页查询语句中,这条语句的效率较高,其他的几种查询形式这里就不讨论了。

原文地址:https://www.cnblogs.com/page-of-Hyman/p/4417609.html