<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" %>
<%@ page import="java.sql.*" %>
<html>
<head>
<title>分页显示数据库记录</title>
</head>
<body>
<div align="center"><strong>分页显示数据库记录</strong></div>
<br><hr>
<table width="800" border="1" align="center">
<tr>
<td>图书名称</td>
<td>出版社</td>
<td>图书价格</td>
</tr>
<%
try
{
String driverName="com.mysql.jdbc.Driver"; //驱动程序名
String userName="root";//数据库用户名
String userPasswd="longchendiao";//密码
String dbName="book";//数据库名
//连接字符串
String url="jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd+"&useUnicode=true&characterEncoding=GB2312";
Class.forName(driverName).newInstance();//加载驱动程序
Connection conn=DriverManager.getConnection(url);
String sql="select * from bookInfo";//创建执行语句
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
int intPageSize; //一页显示的记录数
int intRowCount; //记录的总数
int intPageCount; //总页数
int intPage; //待显示的页码 当前页码
String strPage;
int i;
intPageSize = 3; //设置一页显示的记录数
strPage = request.getParameter("page");//取得待显示的页码
if(strPage == null) //判断strPage是否等于null,如果是,显示第一页数据
{
intPage = 1;
}else{
intPage=java.lang.Integer.parseInt(strPage); //将字符串转换为整型
}
if(intPage < 1)
{
intPage=1;
}
rs.last();//获取记录总数
intRowCount = rs.getRow();
intPageCount = (intRowCount%intPageSize)==0?(intRowCount/intPageSize):(intRowCount/intPageSize + 1); //计算机总页数
if(intPage > intPageCount) intPage = intPageCount; //调整待显示的页码
if(intPageCount>0)
{
rs.absolute((intPage-1)*intPageSize+1); //将记录指针定位到待显示页的第一条记录上
}
//下面用于显示数据
i=0;
while(i<intPageSize && !rs.isAfterLast())
{
%>
<tr>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getString(4)%></td>
</tr>
<%
rs.next();
i++;
}
rs.close();//关闭连接、释放资源
stmt.close();
conn.close();
%>
</table>
<div align="center">
共<%=intRowCount%>个记录,分<%=intPageCount%>页显示,当前页是:第<%=intPage%>页
<%
for(int j=1;j<=intPageCount;j++)
{
out.print(" <a href='MySQLFen.jsp?page="+j+"'>"+j+"</a>");
}
%>
</div>
<%
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<table width="100%" cellspacing="0" cellpadding="4" align="center" bordercolor="#A6CAF0" border=1>
<tr>
<td> <div align="center">
<p>IT在中国电脑学习网!@2007<br>
公司地址:郑州市二七路200号金博大D座2708室 <br />
电话:66202195
电子邮件:<A HREF='mailto:liuhaisong9462@sohu.com'></A> itzcn@126.com </p>
</div></td>
</tr>
</table>
</body>
</html>
jdbc分页
最新推荐文章于 2025-05-30 15:05:53 发布