标签:
思路:定义四个变量
//从数据库中取出数据 //到数据库中去验证 Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; //分页定义变量 int pageNow=1;//当前页 //接受用户的pageNow String spageNow=request.getParameter("pageNow"); if(spageNow!=null){ pageNow=Integer.parseInt(spageNow); } int pageSize=3;//指定显示3条记录 int pageCount=1;//该值是计算出来的 int rowCount=1;//该共有多少记录,数据库计算出来的 try{ //1加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.得到连接 conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/user", "root", "123456"); //算出共有多少页 //1.查询rowcount String sql1 ="select count(*) from user"; ps = conn.prepareStatement(sql1); rs=ps.executeQuery(); rs.next(); rowCount=rs.getInt(1); pageCount=rowCount%pageSize==0?rowCount/pageSize:rowCount/pageSize+1; //3.创建PrepareSatement //请大家思考,如果条件是pageNow=2,pageSize=3 String sql = "select t.* from (select * from user order by id) t limit "+(pageNow-1)*pageSize+","+pageSize+""; //执行操作 ps = conn.prepareStatement(sql); rs=ps.executeQuery(); out.println("<table border=1px bordercolor=green 0 width=500px>"); out.println("<tr><th>ID</th><th>用户名</th><th>密码</th></tr>"); while(rs.next()){ out.println("<tr><td>"+rs.getInt(1)+ "</td><td>"+rs.getString(2)+ "</td><td>"+rs.getString(3)+ "</td></tr>"); } out.println("</table>"); //显示上一页 if(pageNow!=1){ out.println("<a href=‘/LoginServlet/ManageUsers?pageNow="+(pageNow-1)+"‘>上一页</a>"); } //显示分页 for(int i=1;i<=pageCount;i++){ out.println("<a href=‘/LoginServlet/ManageUsers?pageNow="+i+"‘><"+i+"></a>"); } //显示上一页 if(pageNow!=pageCount){ out.println("<a href=‘/LoginServlet/ManageUsers?pageNow="+(pageNow+1)+"‘>下一页</a>"); } //显示分页信息 out.println(" 当前页"+pageNow+"/总页数"+pageCount+"<br>"); out.println("跳转到<input type=‘text‘ id=‘pageNow‘ name=‘pageNow‘><input type=‘button‘ onClick=‘gotoPageNow()‘ value=‘跳‘/>"); }catch(Exception e){ }finally{ if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
标签:
原文地址:http://www.cnblogs.com/sunli0205/p/5884352.html