Java基礎94 分頁查詢(以MySQL數據庫爲例)

一、概述      

  分頁查詢,也可叫作分批查詢,基於數據庫的分頁語句(不一樣數據庫是不一樣的)。
  本文使用的事MySql數據庫。
       假設:每頁顯示10條數據.
       Select * from contact  limit M,N;
       M:開始記錄的索引。第一條數據的索引爲0 (頁數)
       N:一次查詢幾條記錄(每頁顯示的數據的條數)
           則:
             第一頁:select * from contact limit 0,10;
             第二頁:select * from contact limit 10,10
             ............
             第n頁:select * from contact limit(M-1)*N,N;javascript

在MySQL數據庫中的分頁查詢操做https://www.cnblogs.com/dshore123/p/10544241.htmlcss

二、實例演示  

db.properties 配置文件html

1 url=jdbc:mysql://localhost:3306/school
2 user=root
3 password=123456
4 driverClass=com.mysql.jdbc.Driver

JdbcUtil.java 封裝文件(鏈接數據庫)java

 1 package com.shore.util;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.sql.Connection;
 8 import java.sql.DriverManager;
 9 import java.sql.ResultSet;
10 import java.sql.SQLException;
11 import java.sql.Statement;
12 import java.util.Properties;
13 
14 public class JdbcUtil {
15     //鏈接數據庫的URL
16     private static String url=null;
17     private static String user=null;//用戶名
18     private static String password=null;//密碼
19     private static String driverClass=null;
20     //靜態代碼塊中(只加載一次)
21     static{
22         try {
23             //讀取db.properties
24             Properties props=new Properties();
25             InputStream in=JdbcUtil.class.getResourceAsStream("/db.properties");
26             //加載文件
27             props.load(in);
28             url=props.getProperty("url");
29             user=props.getProperty("user");
30             password=props.getProperty("password");
31             driverClass=props.getProperty("driverClass");
32             //註冊驅動
33             Class.forName(driverClass);
34         } catch (FileNotFoundException e) {
35             e.printStackTrace();
36         } catch (IOException e) {
37             e.printStackTrace();
38         } catch (ClassNotFoundException e) {
39             e.printStackTrace();
40             System.out.println("註冊驅動失敗");
41         }
42     }
43     /*
44       * 獲取鏈接
45       * */
46     public static Connection getConnection(){
47         try {
48             Connection conn=DriverManager.getConnection(url, user, password);
49             return conn;
50         } catch (SQLException e) {
51             e.printStackTrace();
52             throw new RuntimeException();
53         }
54     }
55      /*
56       * 釋放資源
57       * */
58     public static void close(Connection conn,Statement stmt,ResultSet rs){
59         try {
60             if(stmt!=null) stmt.close();
61             if(conn!=null) conn.close();
62             if(rs!=null) rs.close();
63         } catch (SQLException e) {
64             e.printStackTrace();
65         }
66     }
67 }

Page 實體類mysql

  1 package com.shore.entity;
  2 
  3 import java.util.List;
  4 
  5 //封裝與分頁有關的全部信息
  6 public class Page {
  7     private List records;//要顯示的分頁記錄
  8     private int currentPageNum;//當前頁碼;可由用戶指定(用於輸入頁碼,點擊跳轉到指定頁)*
  9     private int pageSize = 10;//每頁顯示的記錄條數(這裏是沒頁顯示10條數據) *
 10     private int totalPageNum;//總頁數*
 11     private int prePageNum;//上一頁的頁碼*
 12     private int nextPageNum;//下一頁的頁碼*
 13     
 14     private int startIndex;//數據庫每頁開始記錄的索引(好比第2頁是從11開始,第三頁從21開始...)*
 15     private int totalRecords;//總記錄的條數*
 16     //擴展的
 17     private int startPage;//開始頁碼
 18     private int endPage;//結束頁碼
 19 
 20     private String url;//查詢分頁的請求servlet的地址
 21     
 22     //currentPageNum:用戶要看的頁碼
 23     //totalRecords:總記錄條數
 24     public Page(int currentPageNum,int totalRecords){
 25         this.currentPageNum = currentPageNum;
 26         this.totalRecords = totalRecords;
 27         //計算總頁數
 28         totalPageNum = totalRecords%pageSize==0?totalRecords/pageSize:(totalRecords/pageSize+1);
 29         //計算每頁開始的索引
 30         startIndex = (currentPageNum-1)*pageSize;
 31         //計算開始和結束頁碼:9個頁碼
 32         if(totalPageNum > 9){
 33             //超過9頁
 34             startPage = currentPageNum - 4;
 35             endPage = currentPageNum + 4;
 36             if(startPage < 1){
 37                 startPage = 1;
 38                 endPage = 9;
 39             }
 40             if(endPage>totalPageNum){
 41                 endPage = totalPageNum;
 42                 startPage = endPage - 8;
 43             }            
 44         }else{
 45             //沒有9頁
 46             startPage = 1;
 47             endPage = totalPageNum;
 48         }
 49     }
 50     public List getRecords() {
 51         return records;
 52     }
 53     public void setRecords(List records) {
 54         this.records = records;
 55     }
 56     public int getCurrentPageNum() {
 57         return currentPageNum;
 58     }
 59     public void setCurrentPageNum(int currentPageNum) {
 60         this.currentPageNum = currentPageNum;
 61     }
 62     public int getPageSize() {
 63         return pageSize;
 64     }
 65     public void setPageSize(int pageSize) {
 66         this.pageSize = pageSize;
 67     }
 68     public int getTotalPageNum() {
 69         return totalPageNum;
 70     }
 71     public void setTotalPageNum(int totalPageNum) {
 72         this.totalPageNum = totalPageNum;
 73     }
 74     //不能無限上一頁(假如當前頁是第1頁,那麼「上一頁」這個按鈕變爲灰色,再點擊,則 無反應)
 75     public int getPrePageNum() {
 76         prePageNum = currentPageNum-1;
 77         if(prePageNum < 1){
 78             prePageNum = 1;
 79         }
 80         return prePageNum;
 81     }
 82     public void setPrePageNum(int prePageNum) {
 83         this.prePageNum = prePageNum;
 84     }
 85     //不能無限下一頁(假如當前頁是最後一頁,那麼「下一頁」這個按鈕變爲灰色,再點擊,則 無反應)
 86     public int getNextPageNum() {
 87         nextPageNum = currentPageNum + 1;
 88         if(nextPageNum > totalPageNum){
 89         if(nextPageNum > totalPageNum){
 90             nextPageNum = totalPageNum;
 91         }
 92         return nextPageNum;
 93     }
 94     public void setNextPageNum(int nextPageNum) {
 95         this.nextPageNum = nextPageNum;
 96     }
 97     public int getStartIndex() {
 98         return startIndex;
 99     }
100     public void setStartIndex(int startIndex) {
101         this.startIndex = startIndex;
102     }
103     public int getTotalRecords() {
104         return totalRecords;
105     }
106     public void setTotalRecords(int totalRecords) {
107         this.totalRecords = totalRecords;
108     }
109     public int getStartPage() {
110         return startPage;
111     }
112     public void setStartPage(int startPage) {
113         this.startPage = startPage;
114     }
115     public int getEndPage() {
116         return endPage;
117     }
118     public void setEndPage(int endPage) {
119         this.endPage = endPage;
120     }
121     public String getUrl() {
122         return url;
123     }
124     public void setUrl(String url) {
125         this.url = url;
126     }    
127 }

ContactDAOMySqlImpl 實現類sql

 1 package com.shore.dao.impl;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 
 9 import com.shore.dao.ContactDAO;
10 import com.shore.entity.Contact;
11 import com.shore.util.JdbcUtil;
12 
13 public class ContactDAOMySqlImpl implements ContactDAO{
14 
15     //總記錄數
16     public int getTotalRecordsNum() {
17         Connection conn = null;
18         PreparedStatement stmt = null;
19         ResultSet rs = null;
20         try{
21             //獲取數據庫的鏈接
22             conn = JdbcUtil.getConnection();
23             //準備sql
24             String sql = "select count(*) from contact";
25             //執行預編譯的sql語句(檢查語法)
26             stmt = conn.prepareStatement(sql);
27             //執行sql語句
28             rs = stmt.executeQuery();
29             if(rs.next()){//把查到的結果返回給調用者
30                 return rs.getInt(1);
31             }
32             return 0;
33         }catch(Exception e){
34             throw new RuntimeException(e);
35         }finally{//關閉資源
36             JdbcUtil.close(conn, stmt, rs);
37         }
38     }
39     
40     //每頁的記錄數
41     public List<Contact> getPageRecords(int startIndex, int offset) {
42         Connection conn = null;
43         PreparedStatement stmt = null;
44         ResultSet rs = null;
45         try{
46             //獲取數據庫的鏈接
47             conn = JdbcUtil.getConnection();
48             //執行預編譯的sql語句(檢查語法)
49             stmt = conn.prepareStatement("select * from contact limit ?,?");
50             //設置參數
51             stmt.setInt(1, startIndex);
52             stmt.setInt(2, offset);
53             //發送參數,執行sql
54             rs = stmt.executeQuery();
55             List<Contact> cs = new ArrayList<Contact>();
56             while(rs.next()){
57                 Contact c=new Contact();
58                 c.setId(rs.getString("id"));
59                 c.setName(rs.getString("name"));
60                 c.setSex(rs.getString("sex"));
61                 c.setAge(rs.getInt("age"));
62                 c.setPhone(rs.getString("phone"));
63                 c.setEmail(rs.getString("email"));
64                 c.setQq(rs.getString("qq"));
65                 cs.add(c);
66             }
67             return cs;
68         }catch(Exception e){
69             throw new RuntimeException(e);
70         }finally{//關閉資源
71             JdbcUtil.close(conn, stmt, rs);
72         }
73     }
74 }

ContactServiceimpl 實現類數據庫

 1 package com.shore.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import com.shore.dao.ContactDAO;
 6 import com.shore.dao.impl.ContactDAOMySqlImpl;
 7 import com.shore.entity.Page;
 8 import com.shore.service.ContactService;
 9 
10 public class ContactServiceimpl implements ContactService{
11     ContactDAO dao=new ContactDAOMySqlImpl();
12 
13     public Page findPage(String pageNum) {
14         int num = 1;//用戶要看的頁碼,默認是1
15         if(pageNum!=null&&!pageNum.trim().equals("")){//解析用戶要看的頁碼
16             num = Integer.parseInt(pageNum);
17         }
18         int totalRecords = dao.getTotalRecordsNum();//獲得總記錄的條數
19         Page page = new Page(num, totalRecords);//對象建立出來後,不少的參數就已經計算完畢
20         //查詢分頁的記錄(當前頁顯示的記錄)
21         List records = dao.getPageRecords(page.getStartIndex(), page.getPageSize());
22         page.setRecords(records);
23         return page;
24     }
25 }

ListContactServlet 類jsp

 1 package com.shore.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.shore.entity.Page;
11 import com.shore.service.ContactService;
12 import com.shore.service.impl.ContactServiceimpl;
13 
14 public class ListContactServlet extends HttpServlet {
15     /*
16      * 顯示全部聯繫人的邏輯
17      * */
18     public void doGet(HttpServletRequest request, HttpServletResponse response)
19             throws ServletException, IOException {
20         ContactService service=new ContactServiceimpl();
21         String num=request.getParameter("num");
22         Page page=service.findPage(num);
23         page.setUrl("/ListContactServlet");
24         request.setAttribute("page",page);
25         request.getRequestDispatcher("/listContact.jsp").forward(request, response);
26     }
27 
28     public void doPost(HttpServletRequest request, HttpServletResponse response)
29             throws ServletException, IOException {
30         doGet(request, response);    
31     }
32 }

listContact.jsp 查詢頁面ui

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 <html xmlns="http://www.w3.org/1999/xhtml">
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 7 <title>查詢全部聯繫人</title>
 8 <style type="text/css">
 9     table td{
10         /*文字居中*/
11         text-align:center;
12     }
13     
14     /*合併表格的邊框*/
15     table{
16         border-collapse:collapse;
17     }
18 </style>
19 </head>
20 
21 <body>
22 <center><h3>查詢全部聯繫人</h3></center>
23 <table align="center" border="1" width="700px">
24     <tr>
25         <th>編號</th>
26         <th>姓名</th>
27         <th>性別</th>
28         <th>年齡</th>
29         <th>電話</th>
30         <th>郵箱</th>
31         <th>QQ</th>
32         <th>操做</th>
33     </tr>
34     <c:forEach items="${page.records}" var="con" varStatus="varSta">
35     <tr>
36         <td>${varSta.count }</td>
37         <td>${con.name }</td>
38         <td>${con.sex }</td>
39         <td>${con.age }</td>
40         <td>${con.phone }</td>
41         <td>${con.email }</td>
42         <td>${con.qq }</td>
43         <td><a href="${pageContext.request.contextPath }/QueryContactServlet?id=${con.id}">修改</a>&nbsp;<a href="${pageContext.request.contextPath }/DeleteContactServlet?id=${con.id}">刪除</a></td>
44     </tr>
45     </c:forEach>
46     <tr>
47         <td colspan="8" align="center"><a href="${pageContext.request.contextPath }/addContact.jsp">[添加聯繫人]</a></td>
48     </tr>
49 </table>
50 <%@include file="/common/page.jsp"%>
51 </body>
52 </html>

page.jsp 被包含的頁面this

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <!-- 分頁顯示:開始 -->
 3       
 4       第${page.currentPageNum }頁/共${page.totalPageNum }頁&nbsp;&nbsp;
 5       <a href="${pageContext.request.contextPath}/ListContactServlet?num=1">首頁</a>
 6       <a href="${pageContext.request.contextPath}/ListContactServlet?num=${page.prePageNum}">上一頁</a>
 7       
 8       <c:forEach begin="${page.startPage}" end="${page.endPage}" var="num">
 9           <a href="${pageContext.request.contextPath}/ListContactServlet?num=${num}">${num}</a>
10       </c:forEach>
11       
12       <a href="${pageContext.request.contextPath}/ListContactServlet?num=${page.nextPageNum}">下一頁</a>
13       <a href="${pageContext.request.contextPath}/ListContactServlet?num=${page.totalPageNum }">尾頁</a>
14       
15       &nbsp;&nbsp;
16       <input type="button" id="bt1" value="跳轉到" onclick="jump()"/>&nbsp;<input type="text" size="3" id="num" name="num" />
17       &nbsp;&nbsp;
18       <select name="selNum" onchange="jump1(this)">
19           <c:forEach begin="1" end="${page.totalPageNum }" var="num">
20               <option value="${num}" ${page.currentPageNum==num?'selected="selected"':'' } >${num}</option>
21           </c:forEach>
22       </select>
23       
24       <script type="text/javascript">
25           function jump(){
26               var numValue = document.getElementById("num").value;
27               //驗證
28               if(!/^[1-9][0-9]*$/.test(numValue)){//驗證是不是天然整數
29                   alert("請輸入正確的頁碼");
30                   return;
31               }
32               if(numValue>${page.totalPageNum}){
33                   alert("頁碼不能超過最大頁數");
34                   return;
35               }
36               window.location.href="${pageContext.request.contextPath}/ListContactServlet?num="+numValue;
37           }
38         
39           function jump1(selectObj){
40               window.location.href="${pageContext.request.contextPath}/ListContactServlet?num="+selectObj.value;
41           }
42       </script>
43       
44       <!-- 分頁顯示:結束 -->

最終效果圖:

 

 

 

 

 

 

原創做者:DSHORE

做者主頁:http://www.cnblogs.com/dshore123/

原文出自:http://www.javashuo.com/article/p-tzkfnbnc-m.html

歡迎轉載,轉載務必說明出處。(若是本文對您有幫助,能夠點擊一下右下角的 推薦,或評論,謝謝!

相關文章
相關標籤/搜索