提到分页技术,有四个变量很关键
int rowCount 一共有多少记录 【是从表中查询得来】
int pageSize 每页显示多少记录, 【用户选择 】
int pageCount 一共有多少页 【根据上面两个计算得出的】
int pageNow 希望显示第几页 【这个是用户指定的】
计算pageCount的方法
1 if(rowCount%pageSize==0) 2 { 3 pageCount = rowCount/pageSize; 4 }else{ 5 pageCount = rowCount/pageSize+1; 6 }
SQLServer中数据库中的查询语句为 select top pageSize 字段名列表 from 表名 where id not in ( select top pageSize*(pageNow-1) id from 表名);
MySQL中select * from table limit (start-1)*limit,limit; 其中start是页码,limit是每页显示的条数
1 PrintWriter pw = res.getWriter(); 2 pw.println("<body><center>"); 3 pw.println("<img src=imgs/521.jpg><br>"); 4 pw.println("welcom to my world,u="+u+",p="+p+",s="+s+",sessionId="+sessionId); 5 6 //------------------开始分页-------------------- 7 int rowCount = 0; 8 int pageSize = 3; 9 int pageNow = 1; 10 int pageCount = 0; 11 String sPageNow = req.getParameter("pageNow"); 12 if(sPageNow!=null) 13 { 14 pageNow = Integer.parseInt(sPageNow); 15 } 16 Connection connection = null; 17 PreparedStatement prestatement = null; 18 ResultSet rs = null; 19 try { 20 //加载数据库驱动 21 Class.forName("com.mysql.jdbc.Driver"); 22 //得到连接 23 connection = DriverManager.getConnection("jdbc:mysql://localhost/dbjdbc","root","123456"); 24 //得到statement 25 prestatement = connection.prepareStatement("select count(*) from db_users"); 26 rs = prestatement.executeQuery(); 27 if(rs.next()) 28 { 29 rowCount = rs.getInt(1); 30 } 31 //计算pageCount 32 if(rowCount%pageSize == 0) 33 { 34 pageCount = rowCount/pageSize; 35 }else { 36 pageCount = rowCount/pageSize +1; 37 } 38 39 prestatement = connection.prepareStatement("select * from db_users limit ?,?"); 40 //给?赋值 41 prestatement.setInt(1, pageSize*(pageNow-1)); 42 prestatement.setInt(2, pageSize); 43 rs = prestatement.executeQuery(); 44 45 //显示结果 46 //显示表头 47 48 pw.println("<table border=1>"); 49 pw.println("<tr><th>id</th><th>username</th><th>password</th></tr>"); 50 while(rs.next()) 51 { 52 pw.println("<tr>"); 53 pw.println("<td>"+rs.getInt(1)+"</td>"); 54 pw.println("<td>"+rs.getString(2)+"</td>"); 55 pw.print("<td>"+rs.getString(3)+"</td>"); 56 pw.println("</tr>"); 57 } 58 pw.println("</table>"); 59 //显示上一页 60 if(pageNow!=1) 61 { 62 pw.println("<a href=welcome?pageNow="+(pageNow-1)+">"+"上一页</a>"); 63 } 64 65 //显示超链接 66 for(int i=pageNow;i<=pageCount;i++) 67 { 68 pw.println("<a href=welcome?pageNow="+i+">"+i+"</a>"); 69 } 70 71 72 if(pageNow!=pageCount) 73 { 74 pw.println("<a href=welcome?pageNow="+(pageNow+1)+">"+"下一页</a>"); 75 } 76 pw.println("</center></body>"); 77 } catch (Exception e) { 78 // TODO Auto-generated catch block 79 e.printStackTrace(); 80 }
时间: 2024-11-09 01:57:00