简单的整理了一下分页,希望对初学者有帮助
准备工作:
在Oracle下,建立一张表:
CREATE TABLE mytable(id int, name varchar(32))
/
往表mytable里插入一些值。
testpage.jsp页面程序如下:
<!--
简单的分页示例,demo
-->
<%@page import="java.util.*"%>
<%@page import="java.lang.*"%>
<%@page import="java.io.*"%>
<%@page import="java.sql.*"%>
<%@page import="java.net.*"%>
<%@page contentType="text/html;charset=GBK" %>
<%
String sConn="jdbc:oracle:thin:@host:1521:orcl";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection(sConn,"user","password");
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
//Statement stmtcount=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from mytable");
//String sqlcount="select count(*) from mytable";
//ResultSet rscount=stmtcount.executeQuery(sqlcount);
int pageSize=5; //每页5条
int rowCount=0; //总的记录数
rs.last();
rowCount = rs.getRow();
int pageCount; //总的页数
int currPage = 0; //当前页数
String strPage;
strPage=request.getParameter("page");
if (strPage==null){
currPage=1;
}
else{
currPage=Integer.parseInt(strPage);
if (currPage<1) currPage=1;
}
pageCount=(rowCount+pageSize-1)/pageSize;
if (currPage>pageCount) currPage=pageCount;
int thepage=(currPage-1)*pageSize;
int n=0;
%>
当前为第:<%=currPage%>页<p>
<a href="testpage.jsp?page=1">首 页</a>
<%
if (currPage>1){
%>
<a href="testpage.jsp?page=<%=currPage-1%>">上一页</a>
<%
}
%>
<%
if (currPage<pageCount){
%>
<a href="testpage.jsp?page=<%=currPage+1%>">下一页</a>
<%
}
%>
<a href="testpage.jsp?page=<%=pageCount%>">尾 页</a><p><br><hr>
共<%=rowCount%>条记录 页次:<%=currPage%>/<%=pageCount%>页 <%=pageSize%>条/页
<table width="80%">
<%
if (currPage>0){
rs.absolute(thepage+1);
while (n<pageSize && !rs.isAfterLast()){
out.println("<tr><td>");
out.println(rs.getInt(1)+"</td><td>");
out.println(rs.getString(2)+"</td></tr>");
rs.next();
++n;
}
}
%>
<%
rs.close();
//rscount.close();
stmt.close();
//stmtcount.close();
conn.close();
%>
//偶在Oracle8.1.6上测试,结果能显示出来,但是name字段值给的好像是16进制字节串。但在Oracle8.1.7以后都没问题。可能是jdbc的支持程度不一样。