数据库是mysql
create database bbs;
use bbs;
create table article ( id int primary key auto_increment, pid int, rootid int, title varchar(255), cont text, pdate datetime, isleaf int #1-not leaf 0-leaf );
insert into article values (null, 0, 1, '蚂蚁大战大象', '蚂蚁大战大象', now(), 1); insert into article values (null, 1, 1, '大象被打趴下了', '大象被打趴下了',now(), 1); insert into article values (null, 2, 1, '蚂蚁也不好过','蚂蚁也不好过', now(), 0); insert into article values (null, 2, 1, '瞎说', '瞎说', now(), 1); insert into article values (null, 4, 1, '没有瞎说', '没有瞎说', now(), 0); insert into article values (null, 1, 1, '怎么可能', '怎么可能', now(), 1); insert into article values (null, 6, 1, '怎么没有可能', '怎么没有可能', now(), 0); insert into article values (null, 6, 1, '可能性是很大的', '可能性是很大的', now(), 0); insert into article values (null, 2, 1, '大象进医院了', '大象进医院了', now(), 1); insert into article values (null, 9, 1, '护士是蚂蚁', '护士是蚂蚁', now(), 0); |
<%@ page language="java" contentType="text/html; charset=gbk" pageEncoding="gbk"%> <%@ page import="java.sql.*" %>
<% Connection conn = null; ResultSet rs=null; Statement stmt=null; //定义页数 int pageSize=4; //第一页 int pageNum=1; //sql语句中的分页位置 int startPos=0; //判断是否字符串空,作用是防止第一次运行时会是空的 if(("").equals(request.getParameter("pageNum"))|| null ==request.getParameter("pageNum")){ pageNum=1; }else{ //存储传过来的页数 pageNum=Integer.parseInt(request.getParameter("pageNum")); } //如果出现-1页的情况则转到第一页中 if(pageNum<=0){ pageNum=1; }
try{
Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bbs", "root" , "root");
String sql="select count(*) from article where pid=0"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); rs.next(); //System.out.println("rs.getInt(1)/4)%2==0 =="+((rs.getInt(1)/4)%2==0) ); //这个可以算出一共是几页,也就是最后一面,如果是奇数,那么说明有条不能完整的凑成一页,但他们也得占一页 int totalPage=(rs.getInt(1)/4)%2==0 ? rs.getInt(1)/4+1:rs.getInt(1)/4; //当下一页超过最后一页时,把最后一页给下一页 if(pageNum>totalPage){ pageNum=totalPage; } System.out.println("totalPage"+totalPage); %> <a href=index.jsp?pageNum=1>第一页</a> <a href=index.jsp?pageNum=<%=pageNum-1 %>>上一页</a> <a href=index.jsp?pageNum=<%=pageNum+1 %>>下一页</a> <a href=index.jsp?pageNum=<%=totalPage %>>最后一页</a> <br> <% System.out.println("rs.getInt(1)"+rs.getInt(1)); }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException ex){ ex.printStackTrace(); }
%> <% //因为下面的SQL语句的分页需要开始位置, //每页4条,一共可分7页,这都是从数据库中自己计算出来的结果 startPos=pageSize*(pageNum-1); System.out.println("startPos="+startPos); String sqlStr="select * from article where pid=0 limit "+startPos+", "+pageSize+"; "; stmt=conn.createStatement(); rs=stmt.executeQuery(sqlStr); while(rs.next()){ %><%=rs.getString("title") %><br><% }
%> <!DOCTYPE html PUBLIC "-//W 3C //DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> <title>Insert title here</title> </head> <body>
</body> </html> |