<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" import="java.sql.*" %>
<html>
<head>
<title>JSP连接SQL数据库实现数据分页显示</title>
</head>
<body>
<h1 align="center">JSP连接SQL数据库实现数据分页显示</h1>
<%
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
String user="sa";
String password="123";
Connection conn=DriverManager.getConnection(url,user,password);
Statement stmt=
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from employee";
ResultSet rs=stmt.executeQuery(sql);
int pageSize;//一页显示的记录数
int totalItem;//记录总数
int totalPage;//总页数
int curPage;//待显示页码
String strPage;
int i;
pageSize=10;//设置一页显示的记录数
strPage=request.getParameter("page");//获得待显示页码
if(strPage==null)
{
curPage=1;
}
else
{
curPage=java.lang.Integer.parseInt(strPage);//将字符串转换成×××
}
if(curPage<1)
{
curPage=1;
}
rs.last();//获取记录总数
totalItem=rs.getRow();
totalPage=(totalItem+pageSize-1)/pageSize;
if(curPage>totalPage) curPage=totalPage;//调整待显示的页码
if(totalPage>0)
{//将记录指针到待显示页的第一条记录上
rs.absolute((curPage-1)*pageSize+1);
}
i=0;
%>
<table width="60%" border="1" align="center" bordercolor="#996699" bgcolor="#FFFFFF">
<tr bgcolor="#CCFFFF">
<td align="center">emp_id</td>
<td align="center">fname</td>
<td align="center">minit</td>
<td align="center">lname</td>
<td align="center">job_id</td>
<td align="center">job_lvl</td>
<td align="center">pud_id</td>
<td align="center">hire_date</td>
</tr>
<%//显示数据
while(i<pageSize && !rs.isAfterLast())
{
%>
<tr>
<td><%=rs.getString(1)%></td> <!---取出表中第一个字段-->
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
<td><%=rs.getString(6)%></td>
<td><%=rs.getString(7)%></td>
<td><%=rs.getString(8)%></td>
</tr>
<%
rs.next();
i++;
}
%>
</table><p align="center">
共<%=totalItem%>个记录,分<%=totalPage%>页显示,当前页是:第<%=curPage%>页<br />
<%if(curPage>1){%><a href="page.jsp?page=1">首页</a><%}%>
<%if(curPage>1){%><a href="page.jsp?page=<%=curPage-1%>">上一页</a><%}%>
<%
for(int j=1;j<=totalPage;j++)
{
out.print(" <a href='page.jsp?page="+j+"'>"+j+"</a>");
}
%>
<%if(curPage<totalPage){%><a href="page.jsp?page=<%=curPage+1%>">下一页</a><%}%>
<%if(totalPage>1){%><a href="page.jsp?page=<%=totalPage%>">末页</a><%}%>
<%
rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
转载于:https://blog.51cto.com/congwa/1188867