本例子代碼,只講Oracle分頁的常用的一種方法在Web中的使用,不涉及MVC,代碼優化等東西,高手請飄過。新手可以參考。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
<body>
************************************* Oracle分頁的重要代碼,學習自 韓順平老師的 Java操作Oracle 十二講 **************************************** <br>
<br>
<form action="/TestOracleFenye/index.jsp">
<input type="text" name="pageSize">
<input type="submit" name="submit" value="設置pageSize">
<br/>
</form>
<table>
<tr>
<td>姓名</td>
<td>薪水</td>
</tr>
<%
//加載驅動
Class.forName("oracle.jdbc.driver.OracleDriver");
//建立連接
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@192.168.1.5:1521:BJSXT", "scott","tiger");
//定義結果集
ResultSet rs = null;
//從下面開始和SqlServer 一模一樣
Statement sm = conn.createStatement();
//初始化每頁的記錄條數
int pageSize = 20;
String s_PageSize = request.getParameter("pageSize");
if(s_PageSize!=null && !"".equals(s_PageSize.trim())) {
pageSize = Integer.parseInt(s_PageSize);
}
//總共有多少頁,計算得出
int pageCount = 0;
//總共有多少條記錄,查詢得出
int rowCount = 0;
//當前頁
int currentPage = 1;
//初始化開始和結束的記錄條數
int start = 1;
int end = pageSize;
//得到記錄總數
rs = sm.executeQuery("select count(*) from emp");
while(rs.next()) {
rowCount = rs.getInt(1);
if(rowCount%pageSize==0){
pageCount = rowCount/pageSize;
} else {
pageCount = rowCount/pageSize+1;
}
}
//當前頁碼
String s_CurrentPage = request.getParameter("currentPage");
if(s_CurrentPage!=null && !"".equals(s_CurrentPage.trim())) {
currentPage = Integer.parseInt(s_CurrentPage);
start = (currentPage-1)*pageSize + 1;
end = currentPage*pageSize;
}
//分頁的關鍵代碼
String fenyeSql = "select * from (select a1.*, rownum bieming from (select * from emp) a1 where rownum<=" + end + ") where bieming>=" + start;
out.println(fenyeSql + "<br />");
rs = sm.executeQuery(fenyeSql);
//##查詢所有的員工 rs = sm.executeQuery("select * from emp");
while(rs.next()){
out.print("<tr>");
out.print("<td>" + rs.getString(2) + "</td>");
out.print("<td>" + rs.getString(6) + "</td>");
out.print("</tr>");
}
//打印總頁數
for(int i=1; i<=pageCount; i++){
out.print("<a href='" + basePath + "index.jsp?currentPage=" + i + "&pageSize=" + pageSize +"'>" + i + "</a> ");
}
rs.close();
sm.close();
conn.close();
%>
</table>
</body>
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------