分页查询(六)

流过昼夜 提交于 2020-03-18 17:07:50

一、Oracle分页sql

--分页表select *from emp;
--分页查询
--【1】第一条查询语句带条件
-->1排序(当有条件时加上条件)
select empno,ename,sal from emp where deptno is not null order by sal desc; 
-->2作为一个新的表添加了一个rd列作为分页的序号
select rownum as rd,t.*from (select empno,ename,sal from emp where deptno is not null order by sal desc) t;
-->3分页
select *from (select rownum as rd,t.*from (select empno,ename,sal from emp where deptno is not null order by sal desc) t)k where rd between 1 and 3;
==========================================
(1)select *from (select rownum as rd,t.*from (select empno,ename,sal from emp where deptno is not null order by 
sal desc) t)k where rd between 1 and 3;
(2)select *from (select rownum as rd,t.*from (select empno,ename,sal from emp where deptno is not null order by 
sal desc) t)k where rd>1 and rd<=3;
(3)select *from (select rownum as rd,t.*from (select empno,ename,sal from emp where deptno is not null order by
 sal desc) t where rownum<=3)k where rd>1;---->(2)和(3)是等价的。与(1)不等价。
        -->在Myeclipse中写分页的查询语句:
            stmt =conn.createStatement();
            StringBuffer sql=new StringBuffer("select * from student where 1= 1 ");
            if(name != null && !"".equals(name)){
                sql.append(" and name like '%"+name+"%'");
            }
            if(minScore>0){
                sql.append(" and score >="+minScore);
            }
            sql.append(" order by score desc");
            
            String sql2 = "select  * from (select rownum rn,stu2.* "
                    + "from ("+sql.toString()+" ) stu2 "
                    + "where rownum <="+end+" ) "
                    + "where rn >"+start;
            rs = stmt.executeQuery(sql2);
==========================================================================================
--【2】第一条查询语句不带排序(或条件)
-->1查询
select rownum rn1,stu1.* from student stu; 
-->2分页
select rownum rn2,stu2.* from (
select rownum rn1,stu1.* from student stu1)stu2
where rn1<=10 and rn1>5;
--select rownum,emp.* from emp order by sal desc ;中rownum与order by是死对头,使用了orderby之后,rownum不准确
===========================================================================================
-------------------------------------------------------------------------
--【3】分页中要用到的数据总数和带条件
select * from student;
select count(*) from student;
select * from student where 1=1 and name like '%文%' and score>=76;

注意:需要注意的是在Oracle中根据rownum来分页,而在mysql中是没有rownum的,直接用limit来分页。

二、在项目中的应用

2.1 开发流程

【1】//做法:将分页所需的所有参数都封装到pageBean实体类中<有此工具类,直接调用>,在页面上显示时只需要从
    pageBean中获取属性值即可。
    private int size = 5;//每页显示记录 1 
    private int index = 1;// 当前页号    2           
    private int totalPageCount = 1;// 总页数  3 
    private int totalCount = 0;// 记录总数  4
    private int[] numbers;//展示页数集合  5
    protected List<T> list;//要显示到页面的数据集 6
    -->1,2直接从页面获取;3,5在pageBean中有方法计算获得;需要做的只是数据库中查询数据的条数和数据的集合。
    
【2】/**MVC模式
        Dao层----------->sql语句,得到数据条数和数据集合
        业务逻辑层------>调用Dao层方法,初始化PageBean(给pageBean赋值)
        控制层---------->从页面获取数据,(name,phone,-->模糊查询的参数;index,size),创建pageBean对象,赋值index和size
                         属性,并调用业务层方法,最后跳转页面
        视图层---------->从pageBean中获取数据并显示
        
    */
【3】    //步骤0:项目需求-->  步骤1:数据库表,创建数据库-->步骤2:后台查询数据,初始化pageBean-->步骤3:页面显示
    
    步骤2>
        --1.1>只需要从页面获取两个值(index(当前页数),size(每页的信息条数)--->如果要
              带条件进行查询,则还需要传入条件值(例如姓名和电话-->就则还需要从页面获取
name,phone这两个参数值,));
        --1.2>我们只需要从数据库中得到两个数据-->数据的条数,数据的集合
             oracle数据库与Mysql数据库的查询语句不一样
        --1.3>Mysql    
            //记录条数
                select count(*) from people where name like '%张%' and phone like '%131%';
            //数据集合
                SELECT * from people where name like '%王%' and phone like '%1311%' limit 1,2;     
                //第一个参数是(起始数据的下标索引,或叫做展示数据之前需要去掉的数据)(page-1)*size
                //第二个参数是每页显示的条数
        --1.4Oracle
            //记录条数
            select count(*) from people where name like '%张%' and phone like '%131%';
            //数据集合(不带条件)
            select rownum rn2 ,stu2.*from(
            select rownum rn1 ,stu1.*from student stu1)stu2
            where rn1<=10 and rn1>5;
            //带条件
            select *from (select rownum as rd,t.*from
            (select empno,ename,sal from emp where deptno is not null order by sal desc) t)k 
            where rd between 1 and 3;
============================================
(1)select *from (select rownum as rd,t.*from (select empno,ename,sal from emp where deptno is not null order by 
sal desc) t)k where rd between 1 and 3;
(2)select *from (select rownum as rd,t.*from (select empno,ename,sal from emp where deptno is not null order by 
sal desc) t)k where rd>1 and rd<=3;
(3)select *from (select rownum as rd,t.*from (select empno,ename,sal from emp where deptno is not null order by
 sal desc) t where rownum<=3)k where rd>1;---->(2)和(3)是等价的。与(1)不等价。
        -->在Myeclipse中写分页的查询语句:
            stmt =conn.createStatement();
            StringBuffer sql=new StringBuffer("select * from student where 1= 1 ");
            if(name != null && !"".equals(name)){
                sql.append(" and name like '%"+name+"%'");
            }
            if(minScore>0){
                sql.append(" and score >="+minScore);
            }
            sql.append(" order by score desc");
            
            String sql2 = "select  * from (select rownum rn,stu2.* "
                    + "from ("+sql.toString()+" ) stu2 "
                    + "where rownum <="+end+" ) "
                    + "where rn >"+start;
            rs = stmt.executeQuery(sql2);
            
            
            
            
            

2.2 例子:

查询学生信息功能在页面分页展示

2.2.1 前台

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>查询并显示所有学生信息</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript">
        function changeIndex(size){
            //
            var index = document.getElementById("indexn").value;
            //
            //location.href="/stumanager0/servlet/ShowAllServlet?index="+index+"&size="+size;
            change(index,size);
        }
        /*
        function changeSize(size){
            location.href="/stumanager0/servlet/ShowAllServlet?index=1&size="+size;
        }
        */
        function change1(index,size){
            //location.href="/stumanager0/servlet/ShowAllServlet?index="+index+"&size="+size;
            //修改表单的action属性
            document.forms[0].action="servlet/ShowAllServlet?index="+index+"&size="+size;
            //提交表单
            document.forms[0].submit();
        }
        function change(index,size){
            //给表单index和size表单项赋值value
            document.forms[0].index.value=index;
            document.forms[0].size.value=size;
            //提交表单
            document.forms[0].submit();
        }
    </script>
  </head>
  
  <body> 
  
      <hr>
       <form action="servlet/ShowAllServlet" method="post" id="form1">
           <table align="center">
               <tr>
                   <td>姓名</td>    
                   <td>                   
                       <input type="text" name="name" value="${name }">
                       <input type="hidden" name="index" >
                       <input type="hidden" name="size">
                   </td>
                   <td>分数>=</td>
                   <td><input type="text" name="minScore" value="${minScore }"></td>                   
                   <td><input type="submit" value="提交"></td>
               </tr>
           </table>
       </form>       
       <hr>       
      
    <!-- 显示所有学生   /stumanager/    -->
    <table align="center" border="1" width="60%">
        <tr>
            <th>学生 编号</th>
            <th>学生姓名</th>
            <th>学生年龄</th>
            <th>学生成绩</th>
            <th>vs.index</th>
            <th>更新操作</th>
            <th>删除操作</th>
        </tr>
        <c:forEach items="${pageBean.list}" var="stu" varStatus="vs">
            <tr>
                <td>${stu.id }</td>
                <td>${stu.name }</td>
                <td>${stu.age }</td>
                <td>${stu.score }</td>
                <td>${vs.index }</td>
                <td><a href="/stumanager/servlet/StudentServlet?operate=preupdate&sid=${stu.id}">更新</a></td>
                <td><a href="/stumanager/servlet/StudentServlet?operate=delete&sid=${stu.id}">删除</a></td>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="11" align="center">
                <a href="javascript:change(1,${pageBean.size})">首页</a>&nbsp;
                <c:if test="${pageBean.index !=1 }">
                    <a href="javascript:change(${pageBean.index-1 },${pageBean.size})">上一页</a>&nbsp;
                </c:if>
                <c:if test="${pageBean.index ==1 }">
                    上一页
                </c:if>
                <c:forEach items="${pageBean.numbers }" var="num">
                    <c:if test="${num != pageBean.index  }">
                        <a href="javascript:change(${num },${pageBean.size})">${num }</a>&nbsp;
                    </c:if>
                    <c:if test="${num == pageBean.index  }">
                        [<a href="javascript:change(${num },${pageBean.size})">${num }</a>]&nbsp;                        
                    </c:if>
                </c:forEach>
                <c:if test="${pageBean.index != pageBean.totalPageCount }">
                    <a href="javascript:change(${pageBean.index+1 },${pageBean.size})">下一页</a>&nbsp;                    
                </c:if>
                <c:if test="${pageBean.index ==pageBean.totalPageCount }">
                    下一页
                </c:if>                
                <a href="javascript:change(${pageBean.totalPageCount },${pageBean.size})">末页</a>&nbsp;
                  每页
                    <select id="size" onchange="change(1,this.value)">
                        <c:forEach begin="5" end="25" step="5" var="i">
                            <c:if test="${i==pageBean.size }">
                                <option value="${i }" selected="selected"> ${i }</option>
                            </c:if>
                            <c:if test="${i!= pageBean.size }">
                                <option value="${i }"> ${i }</option>
                            </c:if>
                            
                        </c:forEach>
                    </select>  
                   条记录 
                  直接跳到第<input id="indexn" size="1">页  
                 <input type="button"  value="go" onclick="changeIndex(${pageBean.size})"> 
                   共${pageBean.totalCount }条记录
            </td>
        </tr>
    </table>
   
  </body>
</html>

2.2.2 控制层

package cn.sxt.stmr.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.sxt.stmr.entity.Student;
import cn.sxt.stmr.service.StudentService;
import cn.sxt.stmr.service.impl.StudentServiceImpl;
import cn.sxt.stmr.util.PageBean;

public class ShowAllServlet extends HttpServlet {

    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //1.1获取要查询的页号
        String sindex = request.getParameter("index");//null
        int index = 1;
        try {
            index = Integer.parseInt(sindex);// "2" "1" null "abc"
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        
        //1.2获取每页记录数
        String ssize = request.getParameter("size");//null
        int size = 5;
        try {
            size = Integer.parseInt(ssize);// "2" "1" null "abc"
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //1.3接收查询条件之姓名
        String name = request.getParameter("name");
        if(name==null){
            name="";
        }
        //1.4接收查询条件之最低分
        String sminScore = request.getParameter("minScore");
        if(sminScore==null){
            sminScore="";
        }
        double minScore = 0.0;
        try{
            minScore = Double.parseDouble(sminScore);//null  ""  "abc"    
        }catch(NumberFormatException e){
            e.printStackTrace();
        }
        
        
        
        PageBean pageBean = new PageBean<Student>();
        pageBean.setIndex(index);
        pageBean.setSize(size);
        //2
        StudentService stuService = new StudentServiceImpl();
        //List <Student> stuList =stuService.findAll();        
        //stuService.find(pageBean);
        stuService.find(pageBean,name,minScore);
         
        //3
        request.setAttribute("pageBean",pageBean);//!!!!!!!  
        request.setAttribute("name", name);
        request.setAttribute("minScore", sminScore);
        request.getRequestDispatcher("/jsp/showAll.jsp").forward(request, response); 
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

2.2.3 业务层

接口

package cn.sxt.stmr.service;

import java.util.List;

import cn.sxt.stmr.entity.Student;
import cn.sxt.stmr.util.PageBean;

public interface StudentService {

    /**
     * 查询所有学生
     * @return
     */
    public List<Student> findAll();
    /**
     * 查询指定页的学生
     * @param pageBean
     */
    public void find(PageBean pageBean);
    /**
     * 带条件的分页查询
     * @param pageBean
     * @param name
     * @param minScore
     */
    public void find(PageBean pageBean, String name, double minScore);
    

}

实现类

package cn.sxt.stmr.service.impl;

import java.util.List;

import cn.sxt.stmr.dao.StudentDao;
import cn.sxt.stmr.dao.impl.StudentDaoImpl;
import cn.sxt.stmr.entity.Student;
import cn.sxt.stmr.service.StudentService;
import cn.sxt.stmr.util.PageBean;

public class StudentServiceImpl implements StudentService {

    private StudentDao stuDao = new StudentDaoImpl();    

    public List<Student> findAll() {        
        return this.stuDao.findAll();
    }

    public void find(PageBean pageBean) {
        //1.获取数据库表student记录总数
        //int totalCount = this.stuDao.findAll().size();
        int totalCount = this.stuDao.findCount();
        //2.使用记录总数初始化PageBean(index,size,totalCount,totalPageCount,numbers都有值了,就差list了)
        pageBean.setTotalCount(totalCount);
        
        //3.调用DAO层获取指定页的学生数据并放入pageBean
        /* 5
         * 页号  起始记录   结束记录
         * 1     1   0      5
         * 2     6   5     10
         * 3     11  10     15
         * 4     16  15     20
         * index  >=(index-1)*size+1      <=index*size
         *           >(index-1)*size 
         */
        //int start = (pageBean.getIndex()-1)*pageBean.getSize();
        //int end = pageBean.getIndex()*pageBean.getSize();
        int start = pageBean.getStartRow();
        int end = pageBean.getEndRow();
        List<Student> list = this.stuDao.find(start,end);
        pageBean.setList(list);
        
    }

    public void find(PageBean pageBean, String name, double minScore) {
        //1.获取数据库表student中符合查询条件的记录总数        
        int totalCount = this.stuDao.findCount(name,minScore);
        //2.使用记录总数初始化PageBean(index,size,totalCount,totalPageCount,numbers都有值了,就差list了)
        pageBean.setTotalCount(totalCount);
        
        //3.调用DAO层获取指定页的学生数据并放入pageBean        
        int start = pageBean.getStartRow();
        int end = pageBean.getEndRow();
        List<Student> list = this.stuDao.find(start,end,name,minScore);
        pageBean.setList(list);
        
    }

}

2.2.4工具类

package cn.sxt.stmr.util;

import java.util.List;

/**
 * 分页的三个基本属性
 * 1.每页几条记录size  可以有默认值5
 * 2.当前页号  index    可以有默认值1
 * 3.记录总数totalCount:不可能有默认值,需要查询数据库获取真正的记录总数
 * 
 * 4.一共多少页 :totalPageCount=totalCount/size+1
 *         5  30  31 32 33 34 35  
 * 5.上一页    index-1  当前页1,上一页1
 * 6.下一页   index+1  当前页是最后一页  下一页:还是最后一页
 * 
 * 扩展
 * 分页Bean还可以放要查询的数据  protected List<T> list;
 * 分页Bean还可以放页码列表     [1]  2  3  4  5   private int[] numbers;
 * 
 * @author Administrator
 *
 * @param <T>
 */
public class PageBean<T> {
    private int size = 5;//每页显示记录  //
    private int index = 1;// 当前页号               
    private int totalPageCount = 1;// 总页数   ok
    private int totalCount = 0;// 记录总数      ok
    
    
    private int[] numbers;//展示页数集合  //ok
    protected List<T> list;//要显示到页面的数据集  

    /**
     * 得到开始记录
     * @return
     */
    public int getStartRow() {

        return (index - 1) * size;
    }

    /**
     * 得到结束记录
     * @return
     */
    public int getEndRow() {
        
        return index * size;
    }

    /**
     * @return Returns the size.
     */
    public int getSize() {        
        return size;
    }

    /**
     * @param size
     * The size to set.
     */
    public void setSize(int size) {
        if (size > 0) {
            this.size = size;
        }
    }
    /**
     * @return Returns the currentPageNo.
     */
    public int getIndex() {
        if (totalPageCount == 0) {
            
            return 0;
        }
        
        return index;
    }

    /**
     * @param currentPageNo
     * The currentPageNo to set.
     */
    public void setIndex(int index) {
        if (index > 0) {
            this.index = index;
        }
    }

    /**
     * @return Returns the totalCount.
     */
    public int getTotalCount() {
        return totalCount;
    }

    /**
     * @param totalCount
     *  The totalCount to set.
     */
    public void setTotalCount(int totalCount) {
        if (totalCount >= 0) {
            this.totalCount = totalCount;
            setTotalPageCountByRs();//根据总记录数计算总页�?
        }
    }

    
    public int getTotalPageCount() {
        return this.totalPageCount;
    }

    /**
     * 根据总记录数计算总页�?
     * 5   
     * 20    4
     * 23    5
     */
    private void setTotalPageCountByRs() {
        if (this.size > 0 && this.totalCount > 0 && this.totalCount % this.size == 0) {
            this.totalPageCount = this.totalCount / this.size;
        } else if (this.size > 0 && this.totalCount > 0 && this.totalCount % this.size > 0) {
            this.totalPageCount = (this.totalCount / this.size) + 1;
        } else {
            this.totalPageCount = 0;
        }
        setNumbers(totalPageCount);//获取展示页数集合
    }

    public int[] getNumbers() {
        return numbers;
    }
    
    /**
     * 设置显示页数集合
     * 
     * 默认显示10个页码
     * 41  42  43  44    [45 ]   46  47  48  49  50
     * 
     * 
     *  1 2  3 [4]  5 6 7 8  9  10
     *  
     *  41  42  43  44    45    46  47  [48]  49  50
     * @param totalPageCount
     */
    public void setNumbers(int totalPageCount) {
        if(totalPageCount>0){
            //!.当前数组的长度
            int[] numbers = new int[totalPageCount>10?10:totalPageCount];//页面要显示的页数集合
            int k =0;
            //
            //1.数组长度<10   1 2 3 4 ....   7
            //2.数组长度>=10
            //     当前页<=6  1 2 3 4    10
            //     当前页>=总页数-5           ......12 13 14 15  
            //     其他                                5  6  7 8   9 当前页(10)  10  11 12  13
            for(int i = 0;i < totalPageCount;i++){
                //保证当前页为集合的中�?
                if((i>=index- (numbers.length/2+1) || i >= totalPageCount-numbers.length) && k<numbers.length){
                    numbers[k] = i+1;
                    k++;
                }else if(k>=numbers.length){
                    break;
                }                
            }
            
            this.numbers = numbers;
        }
        
    }
    
    public void setNumbers(int[] numbers) {
        this.numbers = numbers;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }


/*
    public static int getTotalPageCount(int iTotalRecordCount, int iPageSize) {
        if (iPageSize == 0) {
            return 0;
        } else {
            return (iTotalRecordCount % iPageSize) == 0 ? (iTotalRecordCount / iPageSize) : (iTotalRecordCount / iPageSize) + 1;
        }
    }*/
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!