网站建设知识
Mysql学习总结(31)——MySQL分页技术详解
2025-07-22 10:00  点击:0

1.什么是数据分页:数据分页就是将很多条记录像书本一样分页,每页显示多少行记录;

2.为什么要数据分页:当我们进行sql语句查询时,假如数据有成千上万行记录,如果在同一个页面去显示,那这个页面得有多大,数据就要很多,而我们所需的记录又很少,不使用分页,查看起来那么繁琐,而且一不小心容易看着眼花。使用数据分页,就行书本一样,有页数,一目了然。相当简洁。

3.核心sql语句:SELECT * FROM stud LIMIT m,n ————m表示要显示的页数,n表示显示的记录行数

4.核心思想:

  • 总行数(rows): select count(1) from stud;每页显示的行数(PAGE_SIZE): 固定值---已知的一个常量页数: pageSize= num/n + (num%n==0)?0:1 当前页号: currentPage当前要显示的页面数据的起始行号和终止行号 :startRow: (currentPage-1)*pageSize如何显示从startN开始的pageSize条记录 select * from stud limit startN, pageSize;当前显示的开始页号:showStart=currentPage-showSize/2;当前显示的结束页号:showEnd=showStart+showSize-1;模糊查询:select count(*) from stud where 1=1 and........

    5.成果图:

    6.代码实现

    需要的包和配置文件:

    [html] view plain copy
    1. myConUtil.jar----自己写的c3p0pool工具类
    2. commons-dbutils-1.4.jar
    3. mysql-connector-java-5.1.34-bin.jar
    4. c3p0-0.9.1.2.jar
    5. c3p0-config.xml

      index.jsp

      [html] view plain copy
      1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
      2. <%@taglib prefix="c" uri="java.sun/jsp/jstl/core" %>
      3. 查看分页技术
      4. show,jsp

        [html] view plain copy
        学号姓名
        ${stud.id }${stud.name }
        1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
        2. <%@taglib prefix="c" uri="java.sun/jsp/jstl/core"%>
        3. media="screen">
        4. <script type="text/javascript">
        5. function onsub(obj){
        6. window.location.href="https://2cto/database/201608/"+obj.value;
        7. }
        8. </script>
        9. 以下是当前页的内容

          • 请输入要查询的关键字:
          • 学号:
          • 姓名:
      5. 上一页
      6. href="">${idx}
      7. ${idx}
      8. 下一页
      9. table.css

        [html] view plain copy
        1. table{
        2. color: green;
        3. border: 1px solid blue;
        4. border-collapse: collapse;
        5. width:500px;
        6. margin: auto;
        7. }
        8. td{
        9. border: 1px solid blue;
        10. }
        11. th{
        12. border: 1px solid blue;
        13. }
        14. body{
        15. text-align: center;
        16. }

          PageServlet.Java

          [html] view plain copy
          1. package cn.hncu.page1.servlet;
          2. import java.io.IOException;
          3. import java.sql.SQLException;
          4. import java.util.Map;
          5. import javax.servlet.ServletException;
          6. import javax.servlet.http.HttpServlet;
          7. import javax.servlet.http.HttpServletRequest;
          8. import javax.servlet.http.HttpServletResponse;
          9. import cn.hncu.page1.domain.Stud;
          10. import cn.hncu.page1.service.IPageService;
          11. import cn.hncu.page1.service.PageService;
          12. public class PageServlet extends HttpServlet {
          13. private IPageService service=new PageService();
          14. public void doGet(HttpServletRequest request, HttpServletResponse response)
          15. throws ServletException, IOException {
          16. doPost(request, response);
          17. }
          18. public void doPost(HttpServletRequest request, HttpServletResponse response)
          19. throws ServletException, IOException {
          20. request.setCharacterEncoding("utf-8");
          21. //这里是搜索区域的操作
          22. Stud stud=null;
          23. if(request.getMethod().equals("POST")){
          24. if (stud==null) {
          25. stud = new Stud();
          26. }
          27. String serachId = request.getParameter("serachId");
          28. String serachName = request.getParameter("serachName");
          29. stud.setId(serachId);
          30. stud.setName(serachName);
          31. request.getSession().setAttribute("stud", stud);
          32. }else{
          33. stud=(Stud) request.getSession().getAttribute("stud");
          34. if (stud==null) {
          35. stud = new Stud();
          36. }
          37. }
          38. //封装studs对象
          39. int currentPage=1;
          40. try {
          41. currentPage = Integer.parseInt(request.getParameter("page"));
          42. } catch (NumberFormatException e) {
          43. currentPage=1;
          44. }
          45. Map map=null;
          46. try {
          47. map=service.query(currentPage,stud);
          48. } catch (SQLException e) {
          49. e.printStackTrace();
          50. }
          51. map.put("currentPage", currentPage);
          52. //显示滚动页号
          53. int showStart=0;//从第几个页号开始显示
          54. int showEnd=0;//从第几个页号结束显示
          55. int showSize=10;//显示多少页数
          56. int pageCount=Integer.parseInt(""+map.get("pageCount"));
          57. if(showSize>pageCount){//显示页数大于于总页数
          58. showStart=1;
          59. showEnd=pageCount;
          60. }else{
          61. if(currentPage<=showSize/2){
          62. showStart=1;
          63. showEnd=showSize;
          64. }else{
          65. showStart=currentPage-showSize/2;
          66. showEnd=showStart+showSize-1;
          67. }
          68. }
          69. if(showEnd>pageCount){
          70. showEnd=pageCount;
          71. showStart=showEnd-showSize;
          72. }
          73. map.put("showStart", showStart);
          74. map.put("showEnd", showEnd);
          75. request.setAttribute("map", map);
          76. request.getRequestDispatcher("/jsps/show.jsp").forward(request, response);
          77. }
          78. }

            IPageService.java

            [html] view plain copy
            1. package cn.hncu.page1.service;
            2. import java.sql.SQLException;
            3. import java.util.Map;
            4. import cn.hncu.page1.domain.Stud;
            5. public interface IPageService {
            6. public Map query(int currentPage, Stud stud) throws SQLException;
            7. }
            8. PageService.java[html] view plain copy
              1. package cn.hncu.page1.service;
              2. import java.sql.SQLException;
              3. import java.util.Map;
              4. import cn.hncu.page1.dao.PageDao;
              5. import cn.hncu.page1.dao.PageDaoJdbc;
              6. import cn.hncu.page1.domain.Stud;
              7. public class PageService implements IPageService{
              8. private PageDao dao=new PageDaoJdbc();
              9. @Override
              10. public Map query(int currentPage, Stud stud)
              11. throws SQLException {
              12. return dao.query(currentPage,stud);
              13. }
              14. } PageDao.java[html] view plain copy
                1. package cn.hncu.page1.dao;
                2. import java.sql.SQLException;
                3. import java.util.Map;
                4. import cn.hncu.page1.domain.Stud;
                5. public interface PageDao {
                6. public Map query(int currentPage, Stud stud) throws SQLException;
                7. } PageDaoJdbc.java[html] view plain copy
                  1. package cn.hncu.page1.dao;
                  2. import java.sql.SQLException;
                  3. import java.util.HashMap;
                  4. import java.util.List;
                  5. import java.util.Map;
                  6. import javax.sql.DataSource;
                  7. import org.apachemons.dbutils.QueryRunner;
                  8. import org.apachemons.dbutils.handlers.MapListHandler;
                  9. import org.apachemons.dbutils.handlers.ScalarHandler;
                  10. import org.junit.Test;
                  11. import cn.hncu.page1.domain.Stud;
                  12. import cn.hncu.page1.service.IPageService;
                  13. import cn.hncu.pool.C3p0Pool;
                  14. public class PageDaoJdbc implements PageDao{
                  15. private static final int PAGE_SIZE=10;
                  16. @Override
                  17. public Map query(int currentPage, Stud stud) throws SQLException {
                  18. Map map=new HashMap();
                  19. DataSource pool=C3p0Pool.getPool();
                  20. QueryRunner qr=new QueryRunner(pool);
                  21. String sql="select count(*) from stud where 1=1 ";
                  22. if(stud.getId()!=null&&stud.getId().trim().length()>0){
                  23. sql+="and id like '%"+stud.getId()+"%'";
                  24. }
                  25. if(stud.getName()!=null&&stud.getName().trim().length()>0){
                  26. sql+="and name like '%"+stud.getName()+"%'";
                  27. }
                  28. int rows=Integer.parseInt(""+ qr.query(sql, new ScalarHandler()));
                  29. int pageCount=rows/PAGE_SIZE+((rows%PAGE_SIZE==0)?0:1);
                  30. map.put("pageCount", pageCount);
                  31. int startRow=(currentPage-1)*PAGE_SIZE;
                  32. map.put("startRow", startRow);
                  33. String sql2="select * from stud where 1=1 ";//这种判断方法,很不错
                  34. if(stud.getId()!=null&&stud.getId().trim().length()>0){
                  35. sql2+="and id like '%"+stud.getId()+"%'";
                  36. }
                  37. if(stud.getName()!=null&&stud.getName().trim().length()>0){
                  38. sql2+="and name like '%"+stud.getName()+"%' ";
                  39. }
                  40. sql2+="limit "+startRow+" , "+PAGE_SIZE;
                  41. List> datas=qr.query(sql2, new MapListHandler());
                  42. map.put("datas", datas);
                  43. return map;
                  44. }
                  45. }

                    Stud.java

                    [html] view plain copy
                    1. package cn.hncu.page1.domain;
                    2. public class Stud {
                    3. private String id;
                    4. private String name;
                    5. public String getId() {
                    6. return id;
                    7. }
                    8. public void setId(String id) {
                    9. this.id = id;
                    10. }
                    11. public String getName() {
                    12. return name;
                    13. }
                    14. public void setName(String name) {
                    15. this.name = name;
                    16. }
                    17. @Override
                    18. public String toString() {
                    19. return "Stud [id=" + id + ", name=" + name + "]";
                    20. }
                    21. }