<%@ page language="java" %>
<%@ page import="com.mysql.jdbc.Driver" %>
<%@ page import="java.sql.*" %>
<%
?Connection sqlCon; //數(shù)據(jù)庫連接對象
?Statement sqlStmt; //SQL語句對象
?ResultSet sqlRst; //結(jié)果集對象
?String strCon; //數(shù)據(jù)庫連接字符串
?String strSQL; //SQL語句
?int intPageSize; //一頁顯示的記錄數(shù)
?int intRowCount; //記錄總數(shù)
?int intPageCount; //總頁數(shù)
?int intPage; //待顯示頁碼
?String strPage;
?int i;
?intPageSize = 2; //設(shè)置一頁顯示的記錄數(shù)
?strPage = request.getParameter("page"); //取得待顯示頁碼
?if(strPage==null)
?{
??//表明在QueryString中沒有page這一個參數(shù),此時顯示第一頁數(shù)據(jù)
??intPage = 1;
?}
?else
?{
??//將字符串轉(zhuǎn)換成整型
??intPage = java.lang.Integer.parseInt(strPage);
??if(intPage<1) intPage = 1;
?}
?//裝載JDBC驅(qū)動程序
?? //驅(qū)動程序名
?? String driverName="com.mysql.jdbc.Driver";
?? //數(shù)據(jù)庫用戶名
?? String userName="test";
?? //密碼
?? String userPasswd="123456";
?? //數(shù)據(jù)庫名
?
?? String dbName="shujuku";
?? //表名
?? String tableName="biao";
?? //聯(lián)結(jié)字符串
?? String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;
?? Class.forName("com.mysql.jdbc.Driver").newInstance();
?? sqlCon=DriverManager.getConnection(url);
?? //創(chuàng)建語句對象
?
?sqlStmt = sqlCon.createStatement(); //執(zhí)行SQL語句
??? strSQL = "select name from " + tableName;
??? //執(zhí)行SQL語句并獲取結(jié)果集
??? sqlRst = sqlStmt.executeQuery(strSQL);
??? //獲取記錄總數(shù)
?sqlRst.last();
?intRowCount = sqlRst.getRow();
?//記算總頁數(shù)
?intPageCount = (intRowCount+intPageSize-1) / intPageSize;
?//調(diào)整待顯示的頁碼
?if(intPage>intPageCount) intPage = intPageCount;
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>JSP數(shù)據(jù)庫操作例程 - 數(shù)據(jù)分頁顯示 - JDBC 2.0 - mysql</title>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<th>姓名</th>
</tr>
<% if(intPageCount>0)
{
?//將記錄指針定位到待顯示頁的第一條記錄上
?sqlRst.absolute((intPage-1) * intPageSize + 1);
?//顯示數(shù)據(jù)
?i = 0;
?while(i<intPageSize && !sqlRst.isAfterLast()){ %>
<tr>
<td>
<%=sqlRst.getString(1)%>
</td>
</tr>
<% sqlRst.next();
i++;
}
}
%>
</table>
第<%=intPage%>頁 共<%=intPageCount%>頁
<%if(intPage<intPageCount){%><a href="test1.jsp?page=<%=intPage+1%>">下一頁</a><%}%>
<%if(intPage>1){%><a href="test1.jsp?page=<%=intPage-1%>">上一頁</a><%}%>
</body>
</html>
<%
//關(guān)閉結(jié)果集
sqlRst.close();
//關(guān)閉SQL語句對象
sqlStmt.close();
//關(guān)閉數(shù)據(jù)庫
sqlCon.close();
%>
?
?
?