其它常見的方法還有每次翻頁都查詢一次數據庫,從ResultSet中只取出一頁數據(使用rs.last();rs.getRow()獲得總計錄條數,使用rs.absolute()定位到本頁起始記錄)。這種方式在某些數據庫(如oracle)的JDBC實現中差不多也是需要遍歷所有記錄,實驗證明在記錄數很大時速度非常慢。
至於緩存結果集ResultSet的方法則完全是一種錯誤的做法。因爲ResultSet在Statement或Connection關閉時也會被關閉,如果要使ResultSet有效勢必長時間佔用數據庫連接。
因此比較好的分頁做法應該是每次翻頁的時候只從數據庫裏檢索頁面大小的塊區的數據。這樣雖然每次翻頁都需要查詢數據庫,但查詢出的記錄數很少,網絡傳輸數據量不大,如果使用連接池更可以略過最耗時的建立數據庫連接過程。而在數據庫端有各種成熟的優化技術用於提高查詢速度,比在應用服務器層做緩存有效多了。
在oracle數據庫中查詢結果的行號使用僞列ROWNUM表示(從1開始)。例如select * from employee where rownum<10 返回前10條記錄。但因爲rownum是在查詢之後排序之前賦值的,所以查詢employee按birthday排序的第100到120條記錄應該這麼寫:
[pre] select * from (
select my_table.*, rownum as my_rownum from (
select name, birthday from employee order by birthday
) my_table where rownum <120
) where my_rownum>=100
[/pre]
mySQL可以使用LIMIT子句:
select name, birthday from employee order by birthday LIMIT 99,20
DB2有rownumber()函數用於獲取當前行數。
SQL Server沒研究過,可以參考這篇文章:http://www.csdn.net/develop/article/18/18627.shtm
在Web程序中分頁會被頻繁使用,但分頁的實現細節卻是編程過程中比較麻煩的事情。大多分頁顯示的查詢操作都同時需要處理複雜的多重查詢條件,sql語句需要動態拼接組成,再加上分頁需要的記錄定位、總記錄條數查詢以及查詢結果的遍歷、封裝和顯示,程序會變得很複雜並且難以理解。因此需要一些工具類簡化分頁代碼,使程序員專注於業務邏輯部分。下面是我設計的兩個工具類:
PagedStatement 封裝了數據庫連接、總記錄數查詢、分頁查詢、結果數據封裝和關閉數據庫連接等操作,並使用了PreparedStatement支持動態設置參數。
RowSetPage 參考PetStore的page by page iterator模式, 設計RowSetPage用於封裝查詢結果(使用OracleCachedRowSet緩存查詢出的一頁數據,關於使用CachedRowSet封裝數據庫查詢結果請參考JSP頁面查詢顯示常用模式)以及當前頁碼、總記錄條數、當前記錄數等信息, 並且可以生成簡單的HTML分頁代碼。
PagedStatement 查詢的結果封裝成RowsetPage。
下面是簡單的使用示例:
- //DAO查詢數據部分代碼:
- …
- public RowSetPage getEmployee(String gender, int pageNo) throws Exception{
- String sql="select emp_id, emp_code, user_name, real_name from employee where gender =?";
- //使用Oracle數據庫的分頁查詢實現,每頁顯示5條
- PagedStatement pst =new PagedStatementOracleImpl(sql, pageNo, 5);
- pst.setString(1, gender);
- return pst.executeQuery();
- }
- //Servlet處理查詢請求部分代碼:
- …
- int pageNo;
- try{
- //可以通過參數pageno獲得用戶選擇的頁碼
- pageNo = Integer.parseInt(request.getParameter("pageno") );
- }catch(Exception ex){
- //默認爲第一頁
- pageNo=1;
- }
- String gender = request.getParameter("gender" );
- request.setAttribute("empPage", myBean.getEmployee(gender, pageNo) );
- …
- //JSP顯示部分代碼
- <%@ page import = "page.RowSetPage"%>
- …
- <script language="javascript">
- function doQuery(){
- form1.actionType.value="doQuery";
- form1.submit();
- }
- </script>
- …
- <form name=form1 method=get>
- <input type=hidden name=actionType>
- 性別:
- <input type=text name=gender size=1 value="<%=request.getParameter("gender")%>">
- <input type=button value=" 查詢 " onclick="doQuery()">
- <%
- RowSetPage empPage = (RowSetPage)request.getAttribute("empPage");
- if (empPage == null ) empPage = RowSetPage.EMPTY_PAGE;
- %>
- …
- <table cellspacing="0" width="90%">
- <tr> <td>ID</td> <td>代碼</td> <td>用戶名</td> <td>姓名</td> </tr>
- <%
- javax.sql.RowSet empRS = (javax.sql.RowSet) empPage.getRowSet();
- if (empRS!=null) while (empRS.next() ) {
- %>
- <tr>
- <td><%= empRS.getString("EMP_ID")%></td>
- <td><%= empRS.getString("EMP_CODE")%></td>
- <td><%= empRS.getString("USER_NAME")%></td>
- <td><%= empRS.getString("REAL_NAME")%></td>
- </tr>
- <%
- }// end while
- %>
- <tr>
- <%
- //顯示總頁數和當前頁數(pageno)以及分頁代碼。
- //此處doQuery爲頁面上提交查詢動作的javascript函數名, pageno爲標識當前頁碼的參數名
- %>
- <td colspan=4><%= empPage .getHTML("doQuery", "pageno")%></td>
- </tr>
- </table>
- </form>
效果如圖:
因爲分頁顯示一般都會伴有查詢條件和查詢動作,頁面應已經有校驗查詢條件和提交查詢的javascript方法(如上面的doQuery),所以RowSetPage.getHTML()生成的分頁代碼在用戶選擇新頁碼時直接回調前面的處理提交查詢的javascript方法。注意在顯示查詢結果的時候上次的查詢條件也需要保持,如<input type=text name=gender size=1 value="<%=request.getParameter("gender")%>">。同時由於頁碼的參數名可以指定,因此也支持在同一頁面中有多個分頁區。
另一種分頁代碼實現是生成每一頁的URL,將查詢參數和頁碼作爲QueryString附在URL後面。這種方法的缺陷是在查詢條件比較複雜時難以處理,並且需要指定處理查詢動作的servlet,可能不適合某些定製的查詢操作。
如果對RowSetPage.getHTML()生成的默認分頁代碼不滿意可以編寫自己的分頁處理代碼,RowSetPage提供了很多getter方法用於獲取相關信息(如當前頁碼、總頁數、 總記錄數和當前記錄數等)。
在實際應用中可以將分頁查詢和顯示做成jsp taglib, 進一步簡化JSP代碼,屏蔽Java Code。
附:分頁工具類的源代碼, 有註釋,應該很容易理解。
1.Page.java
2.RowSetPage.java(RowSetPage繼承Page)
3.PagedStatement.java
4.PagedStatementOracleImpl.java(PagedStatementOracleImpl繼承PagedStatement)
您可以任意使用這些源代碼,但必須保留author [email protected]字樣
- ///////////////////////////////////
- //
- // Page.java
- // author: [email protected]
- //
- ///////////////////////////////////
- package page;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Collections;
- /**
- * Title: 分頁對象<br>
- * Description: 用於包含數據及分頁信息的對象<br>
- * Page類實現了用於顯示分頁信息的基本方法,但未指定所含數據的類型,
- * 可根據需要實現以特定方式組織數據的子類,<br>
- * 如RowSetPage以RowSet封裝數據,ListPage以List封裝數據<br>
- * Copyright: Copyright (c) 2002 <br>
- * @author [email protected] <br>
- * @version 1.0
- */
- public class Page implements java.io.Serializable {
- public static final Page EMPTY_PAGE = new Page();
- public static final int DEFAULT_PAGE_SIZE = 20;
- public static final int MAX_PAGE_SIZE = 9999;
- private int myPageSize = DEFAULT_PAGE_SIZE;
- private int start;
- private int avaCount,totalSize;
- private Object data;
- private int currentPageno;
- private int totalPageCount;
- /**
- * 默認構造方法,只構造空頁
- */
- protected Page(){
- this.init(0,0,0,DEFAULT_PAGE_SIZE,new Object());
- }
- /**
- * 分頁數據初始方法,由子類調用
- * @param start 本頁數據在數據庫中的起始位置
- * @param avaCount 本頁包含的數據條數
- * @param totalSize 數據庫中總記錄條數
- * @param pageSize 本頁容量
- * @param data 本頁包含的數據
- */
- protected void init(int start, int avaCount, int totalSize, int pageSize, Object data){
- this.avaCount =avaCount;
- this.myPageSize = pageSize;
- this.start = start;
- this.totalSize = totalSize;
- this.data=data;
- //System.out.println("avaCount:"+avaCount);
- //System.out.println("totalSize:"+totalSize);
- if (avaCount>totalSize) {
- //throw new RuntimeException("記錄條數大於總條數?!");
- }
- this.currentPageno = (start -1)/pageSize +1;
- this.totalPageCount = (totalSize + pageSize -1) / pageSize;
- if (totalSize==0 && avaCount==0){
- this.currentPageno = 1;
- this.totalPageCount = 1;
- }
- //System.out.println("Start Index to Page No: " + start + "-" + currentPageno);
- }
- public Object getData(){
- return this.data;
- }
- /**
- * 取本頁數據容量(本頁能包含的記錄數)
- * @return 本頁能包含的記錄數
- */
- public int getPageSize(){
- return this.myPageSize;
- }
- /**
- * 是否有下一頁
- * @return 是否有下一頁
- */
- public boolean hasNextPage() {
- /*
- if (avaCount==0 && totalSize==0){
- return false;
- }
- return (start + avaCount -1) < totalSize;
- */
- return (this.getCurrentPageNo()<this.getTotalPageCount());
- }
- /**
- * 是否有上一頁
- * @return 是否有上一頁
- */
- public boolean hasPreviousPage() {
- /*
- return start > 1;
- */
- return (this.getCurrentPageNo()>1);
- }
- /**
- * 獲取當前頁第一條數據在數據庫中的位置
- * @return
- */
- public int getStart(){
- return start;
- }
- /**
- * 獲取當前頁最後一條數據在數據庫中的位置
- * @return
- */
- public int getEnd(){
- int end = this.getStart() + this.getSize() -1;
- if (end<0) {
- end = 0;
- }
- return end;
- }
- /**
- * 獲取上一頁第一條數據在數據庫中的位置
- * @return 記錄對應的rownum
- */
- public int getStartOfPreviousPage() {
- return Math.max(start-myPageSize, 1);
- }
- /**
- * 獲取下一頁第一條數據在數據庫中的位置
- * @return 記錄對應的rownum
- */
- public int getStartOfNextPage() {
- return start + avaCount;
- }
- /**
- * 獲取任一頁第一條數據在數據庫中的位置,每頁條數使用默認值
- * @param pageNo 頁號
- * @return 記錄對應的rownum
- */
- public static int getStartOfAnyPage(int pageNo){
- return getStartOfAnyPage(pageNo, DEFAULT_PAGE_SIZE);
- }
- /**
- * 獲取任一頁第一條數據在數據庫中的位置
- * @param pageNo 頁號
- * @param pageSize 每頁包含的記錄數
- * @return 記錄對應的rownum
- */
- public static int getStartOfAnyPage(int pageNo, int pageSize){
- int startIndex = (pageNo-1) * pageSize + 1;
- if ( startIndex < 1) startIndex = 1;
- //System.out.println("Page No to Start Index: " + pageNo + "-" + startIndex);
- return startIndex;
- }
- /**
- * 取本頁包含的記錄數
- * @return 本頁包含的記錄數
- */
- public int getSize() {
- return avaCount;
- }
- /**
- * 取數據庫中包含的總記錄數
- * @return 數據庫中包含的總記錄數
- */
- public int getTotalSize() {
- return this.totalSize;
- }
- /**
- * 取當前頁碼
- * @return 當前頁碼
- */
- public int getCurrentPageNo(){
- return this.currentPageno;
- }
- /**
- * 取總頁碼
- * @return 總頁碼
- */
- public int getTotalPageCount(){
- return this.totalPageCount;
- }
- /**
- *
- * @param queryJSFunctionName 實現分頁的JS腳本名字,頁碼變動時會自動回調該方法
- * @param pageNoParamName 頁碼參數名稱
- * @return
- */
- public String getHTML(String queryJSFunctionName, String pageNoParamName){
- if (getTotalPageCount()<1){
- return "<input type='hidden' name='"+pageNoParamName+"' value='1' >";
- }
- if (queryJSFunctionName == null || queryJSFunctionName.trim().length()<1) {
- queryJSFunctionName = "gotoPage";
- }
- if (pageNoParamName == null || pageNoParamName.trim().length()<1){
- pageNoParamName = "pageno";
- }
- String gotoPage = "_"+queryJSFunctionName;
- StringBuffer html = new StringBuffer("/n");
- html.append("<script language=/"Javascript1.2/">/n")
- .append("function ").append(gotoPage).append("(pageNo){ /n")
- .append( " var curPage=1; /n")
- .append( " try{ curPage = document.all[/"")
- .append(pageNoParamName).append("/"].value; /n")
- .append( " document.all[/"").append(pageNoParamName)
- .append("/"].value = pageNo; /n")
- .append( " ").append(queryJSFunctionName).append("(pageNo); /n")
- .append( " return true; /n")
- .append( " }catch(e){ /n")
- // .append( " try{ /n")
- // .append( " document.forms[0].submit(); /n")
- // .append( " }catch(e){ /n")
- .append( " alert('尚未定義查詢方法:function ")
- .append(queryJSFunctionName).append("()'); /n")
- .append( " document.all[/"").append(pageNoParamName)
- .append("/"].value = curPage; /n")
- .append( " return false; /n")
- // .append( " } /n")
- .append( " } /n")
- .append( "}")
- .append( "</script> /n")
- .append( "");
- html.append( "<table border=0 cellspacing=0 cellpadding=0 align=center width=80%> /n")
- .append( " <tr> /n")
- .append( " <td align=left><br> /n");
- html.append( " 共" ).append( getTotalPageCount() ).append( "頁")
- .append( " [") .append(getStart()).append("..").append(getEnd())
- .append("/").append(this.getTotalSize()).append("] /n")
- .append( " </td> /n")
- .append( " <td align=right> /n");
- if (hasPreviousPage()){
- html.append( "[<a href='javascript:").append(gotoPage)
- .append("(") .append(getCurrentPageNo()-1)
- .append( ")'>上一頁</a>] /n");
- }
- html.append( " 第")
- .append( " <select name='")
- .append(pageNoParamName).append("' onChange='javascript:")
- .append(gotoPage).append("(this.value)'>/n");
- String selected = "selected";
- for(int i=1;i<=getTotalPageCount();i++){
- if( i == getCurrentPageNo() )
- selected = "selected";
- else selected = "";
- html.append( " <option value='").append(i).append("' ")
- .append(selected).append(">").append(i).append("</option> /n");
- }
- if (getCurrentPageNo()>getTotalPageCount()){
- html.append( " <option value='").append(getCurrentPageNo())
- .append("' selected>").append(getCurrentPageNo())
- .append("</option> /n");
- }
- html.append( " </select>頁 /n");
- if (hasNextPage()){
- html.append( " [<a href='javascript:").append(gotoPage)
- .append("(").append((getCurrentPageNo()+1))
- .append( ")'>下一頁</a>] /n");
- }
- html.append( "</td></tr></table> /n");
- return html.toString();
- }
- }
- ///////////////////////////////////
- //
- // RowSetPage.java
- // author: [email protected]
- //
- ///////////////////////////////////
- package page;
- import javax.sql.RowSet;
- /**
- * <p>Title: RowSetPage</p>
- * <p>Description: 使用RowSet封裝數據的分頁對象</p>
- * <p>Copyright: Copyright (c) 2003</p>
- * @author [email protected]
- * @version 1.0
- */
- public class RowSetPage extends Page {
- private javax.sql.RowSet rs;
- /**
- *空頁
- */
- public static final RowSetPage EMPTY_PAGE = new RowSetPage();
- /**
- *默認構造方法,創建空頁
- */
- public RowSetPage(){
- this(null, 0,0);
- }
- /**
- *構造分頁對象
- *@param crs 包含一頁數據的OracleCachedRowSet
- *@param start 該頁數據在數據庫中的起始位置
- *@param totalSize 數據庫中包含的記錄總數
- */
- public RowSetPage(RowSet crs, int start, int totalSize) {
- this(crs,start,totalSize,Page.DEFAULT_PAGE_SIZE);
- }
- /**
- *構造分頁對象
- *@param crs 包含一頁數據的OracleCachedRowSet
- *@param start 該頁數據在數據庫中的起始位置
- *@param totalSize 數據庫中包含的記錄總數
- *@pageSize 本頁能容納的記錄數
- */
- public RowSetPage(RowSet crs, int start, int totalSize, int pageSize) {
- try{
- int avaCount=0;
- if (crs!=null) {
- crs.beforeFirst();
- if (crs.next()){
- crs.last();
- avaCount = crs.getRow();
- }
- crs.beforeFirst();
- }
- rs = crs;
- super.init(start,avaCount,totalSize,pageSize,rs);
- }catch(java.sql.SQLException sqle){
- throw new RuntimeException(sqle.toString());
- }
- }
- /**
- *取分頁對象中的記錄數據
- */
- public javax.sql.RowSet getRowSet(){
- return rs;
- }
- }
- ///////////////////////////////////
- //
- // PagedStatement.java
- // author: [email protected]
- //
- ///////////////////////////////////
- package page;
- import foo.DBUtil;
- import java.math.BigDecimal;
- import java.util.List;
- import java.util.Iterator;
- import java.util.Collections;
- import java.sql.Connection;
- import java.sql.SQLException;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import java.sql.PreparedStatement;
- import java.sql.Timestamp;
- import javax.sql.RowSet;
- /**
- * <p>Title: 分頁查詢</p>
- * <p>Description: 根據查詢語句和頁碼查詢出當頁數據</p>
- * <p>Copyright: Copyright (c) 2002</p>
- * @author [email protected]
- * @version 1.0
- */
- public abstract class PagedStatement {
- public final static int MAX_PAGE_SIZE = Page.MAX_PAGE_SIZE;
- protected String countSQL, querySQL;
- protected int pageNo,pageSize,startIndex,totalCount;
- protected javax.sql.RowSet rowSet;
- protected RowSetPage rowSetPage;
- private List boundParams;
- /**
- * 構造一查詢出所有數據的PageStatement
- * @param sql query sql
- */
- public PagedStatement(String sql){
- this(sql,1,MAX_PAGE_SIZE);
- }
- /**
- * 構造一查詢出當頁數據的PageStatement
- * @param sql query sql
- * @param pageNo 頁碼
- */
- public PagedStatement(String sql, int pageNo){
- this(sql, pageNo, Page.DEFAULT_PAGE_SIZE);
- }
- /**
- * 構造一查詢出當頁數據的PageStatement,並指定每頁顯示記錄條數
- * @param sql query sql
- * @param pageNo 頁碼
- * @param pageSize 每頁容量
- */
- public PagedStatement(String sql, int pageNo, int pageSize){
- this.pageNo = pageNo;
- this.pageSize = pageSize;
- this.startIndex = Page.getStartOfAnyPage(pageNo, pageSize);
- this.boundParams = Collections.synchronizedList(new java.util.LinkedList());
- this.countSQL = "select count(*) from ( " + sql +") ";
- this.querySQL = intiQuerySQL(sql, this.startIndex, pageSize);
- }
- /**
- *生成查詢一頁數據的sql語句
- *@param sql 原查詢語句
- *@startIndex 開始記錄位置
- *@size 需要獲取的記錄數
- */
- protected abstract String intiQuerySQL(String sql, int startIndex, int size);
- /**
- *使用給出的對象設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param obj 包含參數值的對象
- */
- public void setObject(int index, Object obj) throws SQLException{
- BoundParam bp = new BoundParam(index, obj);
- boundParams.remove(bp);
- boundParams.add( bp);
- }
- /**
- *使用給出的對象設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param obj 包含參數值的對象
- *@param targetSqlType 參數的數據庫類型
- */
- public void setObject(int index, Object obj, int targetSqlType) throws SQLException{
- BoundParam bp = new BoundParam(index, obj, targetSqlType);
- boundParams.remove(bp);
- boundParams.add(bp );
- }
- /**
- *使用給出的對象設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param obj 包含參數值的對象
- *@param targetSqlType 參數的數據庫類型(常量定義在java.sql.Types中)
- *@param scale 精度,小數點後的位數
- * (只對targetSqlType是Types.NUMBER或Types.DECIMAL有效,其它類型則忽略)
- */
- public void setObject(int index, Object obj, int targetSqlType, int scale) throws SQLException{
- BoundParam bp = new BoundParam(index, obj, targetSqlType, scale) ;
- boundParams.remove(bp);
- boundParams.add(bp);
- }
- /**
- *使用給出的字符串設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param str 包含參數值的字符串
- */
- public void setString(int index, String str)throws SQLException{
- BoundParam bp = new BoundParam(index, str) ;
- boundParams.remove(bp);
- boundParams.add(bp);
- }
- /**
- *使用給出的字符串設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param timestamp 包含參數值的時間戳
- */
- public void setTimestamp(int index, Timestamp timestamp)throws SQLException{
- BoundParam bp = new BoundParam(index, timestamp) ;
- boundParams.remove(bp);
- boundParams.add( bp );
- }
- /**
- *使用給出的整數設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param value 包含參數值的整數
- */
- public void setInt(int index, int value)throws SQLException{
- BoundParam bp = new BoundParam(index, new Integer(value)) ;
- boundParams.remove(bp);
- boundParams.add( bp );
- }
- /**
- *使用給出的長整數設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param value 包含參數值的長整數
- */
- public void setLong(int index, long value)throws SQLException{
- BoundParam bp = new BoundParam(index, new Long(value)) ;
- boundParams.remove(bp);
- boundParams.add( bp );
- }
- /**
- *使用給出的雙精度浮點數設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param value 包含參數值的雙精度浮點數
- */
- public void setDouble(int index, double value)throws SQLException{
- BoundParam bp = new BoundParam(index, new Double(value)) ;
- boundParams.remove(bp);
- boundParams.add( bp);
- }
- /**
- *使用給出的BigDecimal設置指定參數的值
- *@param index 第一個參數爲1,第二個爲2,。。。
- *@param bd 包含參數值的BigDecimal
- */
- public void setBigDecimal(int index, BigDecimal bd)throws SQLException{
- BoundParam bp = new BoundParam(index, bd ) ;
- boundParams.remove(bp);
- boundParams.add( bp);
- }
- private void setParams(PreparedStatement pst) throws SQLException{
- if (pst==null || this.boundParams==null || this.boundParams.size()==0 ) return ;
- BoundParam param;
- for (Iterator itr = this.boundParams.iterator();itr.hasNext();){
- param = (BoundParam) itr.next();
- if (param==null) continue;
- if (param.sqlType == java.sql.Types.OTHER){
- pst.setObject(param.index, param.value);
- }else{
- pst.setObject(param.index, param.value, param.sqlType, param.scale);
- }
- }
- }
- /**
- * 執行查詢取得一頁數據,執行結束後關閉數據庫連接
- * @return RowSetPage
- * @throws SQLException
- */
- public RowSetPage executeQuery() throws SQLException{
- System.out.println("executeQueryUsingPreparedStatement");
- Connection conn = DBUtil.getConnection();
- PreparedStatement pst = null;
- ResultSet rs = null;
- try{
- pst = conn.prepareStatement(this.countSQL);
- setParams(pst);
- rs =pst.executeQuery();
- if (rs.next()){
- totalCount = rs.getInt(1);
- } else {
- totalCount = 0;
- }
- rs.close();
- pst.close();
- if (totalCount < 1 ) return RowSetPage.EMPTY_PAGE;
- pst = conn.prepareStatement(this.querySQL);
- System.out.println(querySQL);
- pst.setFetchSize(this.pageSize);
- setParams(pst);
- rs =pst.executeQuery();
- //rs.setFetchSize(pageSize);
- this.rowSet = populate(rs);
- rs.close();
- rs = null;
- pst.close();
- pst = null;
- this.rowSetPage = new RowSetPage(this.rowSet,startIndex,totalCount,pageSize);
- return this.rowSetPage;
- }catch(SQLException sqle){
- //System.out.println("executeQuery SQLException");
- sqle.printStackTrace();
- throw sqle;
- }catch(Exception e){
- e.printStackTrace();
- throw new RuntimeException(e.toString());
- }finally{
- //System.out.println("executeQuery finally");
- DBUtil.close(rs, pst, conn);
- }
- }
- /**
- *將ResultSet數據填充進CachedRowSet
- */
- protected abstract RowSet populate(ResultSet rs) throws SQLException;
- /**
- *取封裝成RowSet查詢結果
- *@return RowSet
- */
- public javax.sql.RowSet getRowSet(){
- return this.rowSet;
- }
- /**
- *取封裝成RowSetPage的查詢結果
- *@return RowSetPage
- */
- public RowSetPage getRowSetPage() {
- return this.rowSetPage;
- }
- /**
- *關閉數據庫連接
- */
- public void close(){
- //因爲數據庫連接在查詢結束或發生異常時即關閉,此處不做任何事情
- //留待擴充。
- }
- private class BoundParam {
- int index;
- Object value;
- int sqlType;
- int scale;
- public BoundParam(int index, Object value) {
- this(index, value, java.sql.Types.OTHER);
- }
- public BoundParam(int index, Object value, int sqlType) {
- this(index, value, sqlType, 0);
- }
- public BoundParam(int index, Object value, int sqlType, int scale) {
- this.index = index;
- this.value = value;
- this.sqlType = sqlType;
- this.scale = scale;
- }
- public boolean equals(Object obj){
- if (obj!=null && this.getClass().isInstance(obj)){
- BoundParam bp = (BoundParam)obj;
- if (this.index==bp.index) return true;
- }
- return false;
- }
- }
- }
- ///////////////////////////////////
- //
- // PagedStatementOracleImpl.java
- // author: [email protected]
- //
- ///////////////////////////////////
- package page;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import javax.sql.RowSet;
- import oracle.jdbc.rowset.OracleCachedRowSet;
- /**
- * <p>Title: 分頁查詢Oracle數據庫實現</p>
- * <p>Copyright: Copyright (c) 2002</p>
- * @author [email protected]
- * @version 1.0
- */
- public class PagedStatementOracleImpl extends PagedStatement {
- /**
- * 構造一查詢出所有數據的PageStatement
- * @param sql query sql
- */
- public PagedStatementOracleImpl(String sql){
- super(sql);
- }
- /**
- * 構造一查詢出當頁數據的PageStatement
- * @param sql query sql
- * @param pageNo 頁碼
- */
- public PagedStatementOracleImpl(String sql, int pageNo){
- super(sql, pageNo);
- }
- /**
- * 構造一查詢出當頁數據的PageStatement,並指定每頁顯示記錄條數
- * @param sql query sql
- * @param pageNo 頁碼
- * @param pageSize 每頁容量
- */
- public PagedStatementOracleImpl(String sql, int pageNo, int pageSize){
- super(sql, pageNo, pageSize);
- }
- /**
- *生成查詢一頁數據的sql語句
- *@param sql 原查詢語句
- *@startIndex 開始記錄位置
- *@size 需要獲取的記錄數
- */
- protected String intiQuerySQL(String sql, int startIndex, int size){
- StringBuffer querySQL = new StringBuffer();
- if (size != super.MAX_PAGE_SIZE) {
- querySQL.append("select * from (select my_table.*,rownum as my_rownum from(")
- .append( sql)
- .append(") my_table where rownum<").append(startIndex + size)
- .append(") where my_rownum>=").append(startIndex);
- } else {
- querySQL.append("select * from (select my_table.*,rownum as my_rownum from(")
- .append(sql)
- .append(") my_table ")
- .append(") where my_rownum>=").append(startIndex);
- }
- return querySQL.toString();
- }
- /**
- *將ResultSet數據填充進CachedRowSet
- */
- protected RowSet populate(ResultSet rs) throws SQLException{
- OracleCachedRowSet ocrs = new OracleCachedRowSet();
- ocrs.populate(rs);
- return ocrs;
- }
- } ***********************************************************************************************************************
- 下面是用javabean和jsp頁面來實現數據的分頁顯示,例子中所使用的數據庫是Mysql.
- 類名:
databaseBean.java:
以下爲databaseBean.java的代碼:
package loan;
import java.sql.*;
import java.util.*; - public class databaseBean
{
//這是默認的數據庫連接方式
private String DBLocation="jdbc:mysql://localhost/loan?user=root&password=password&useUnicode=true&characterEncoding=GB2312";
private String DBDriver="com.mysql.jdbc.Driver";
private Connection conn=null;
public databaseBean(){} - //通過set方法可以靈活設置數據庫的連接
public void setDBLocation(String location){DBLocation=location;}
public void setDBDriver(String driver){DBDriver=driver;}
public void setconn(Connection conn){this.conn=conn;} - public String getDBLocation(){return(DBLocation);}
public String getDBDriver(){return(DBDriver);}
public Connection getconn(){return(conn);} - /*public String DBConnect(){}
public String DBDisconnect(){}
public ResultSet query(String sql){}
public int getTotalPage(String sql,int pageSize){}
public ResultSet getPagedRs(String sql,int pageSize,int pageNumber){}
public String execute_sql(String sql){}*/ - //建立連接
public String DBConnect()
{
String strExc="Success!";//strExc默認爲Success,如果有例外拋出,即數據庫連接不成功,則下面幾個catch中被賦予其他拋出信息
try
{
Class.forName(DBDriver);
conn=DriverManager.getConnection(DBLocation);
}
catch(ClassNotFoundException e)
{
strExc="數據庫驅動沒有找到,錯誤提示:<br>" +e.toString();
}
catch(SQLException e)
{ - strExc="sql語句錯誤,錯誤提示<br>" +e.toString();
}
catch(Exception e)
{
strExc="錯誤提示:<br>" +e.toString();
} - return (strExc);
}//then end of DBConnect - //斷開連接
public String DBDisconnect()
{
String strExc="Success!";//strExc默認爲Success,如果有例外拋出,即數據庫斷開連接不成功,則下面幾個catch中被賦予其他拋出信息 - try
{
if(conn!=null)conn.close();
}
catch(SQLException e)
{
strExc=e.toString();
}
return (strExc); - }
- //通過傳入sql語句來返回一個結果集
public ResultSet query(String sql) throws SQLException,Exception
{
ResultSet rs=null;
if (conn==null)
{
DBConnect();
} - if (conn==null)
{
rs=null;
}
else
{
try
{
Statement s=conn.createStatement();
rs=s.executeQuery(sql);
}
catch(SQLException e){throw new SQLException("Cound not execute query.");}
catch(Exception e){throw new Exception("Cound not execute query.");}
}//then end of if
return(rs);
}//then end of the function executeQuery - //通過傳入sql語句和pageSize(每頁所顯示的結果數目)計算並返回總共的頁數
public int getTotalPage(String sql,int pageSize)
{
ResultSet rs=null;
int totalRows=0;
if (conn==null)
{
DBConnect();
} - if (conn==null)
{
rs=null;
}
else
try
{
Statement s=conn.createStatement(); - rs=s.executeQuery(sql);//通過傳入的sql得到結果集
- while(rs.next())
totalRows++;//讓rs一個個數,數完一遍,通過totalRows++也就計算出了返回結果集中總的條目數
}
catch(SQLException e){} - rs=null;
//由這個算法得出總頁數(totalRows-1)/pageSize+1,並返回結果。totalRows是指返回結果集中的總的條目數,pageSize是指每頁顯示的條目數
return((totalRows-1)/pageSize+1);
}
//通過傳入sql語句,每頁顯示的條目數(pageSize)和頁碼,得到一個結果集
public ResultSet getPagedRs(String sql,int pageSize,int pageNumber)
{
ResultSet rs=null;
int absoluteLocation;
if (conn==null)
{
DBConnect();
}- if (conn==null)
{
rs=null;
}
else
try
{
Statement s=conn.createStatement(); - //pageSize*pageNumber每頁顯示的條目數乘以頁碼,計算出最後一行結果的編號,任何編號大於這個maxrows的結果都會被drop
s.setMaxRows(pageSize*pageNumber); - rs=s.executeQuery(sql);
}
catch(SQLException e){} - //absoluteLocation=pageSize*(pageNumber-1)這個表達式計算出上一頁最後一個結果的編號(如果有本頁的話,上一頁的顯示的結果條目數肯定是pageSize)
absoluteLocation=pageSize*(pageNumber-1);
try
{- //這個for循環的作用是讓結果集rs定位到本頁之前的最後一個結果處
for(int i=0;i<absoluteLocation;i++)
{
rs.next();
}
}
catch(SQLException e) { }
//此時返回的結果集被兩頭一夾,就是該頁(pageNumber)要顯示的結果
return(rs); - }
public String execute_sql(String sql){
String strExc;
strExc="Success!";- if(conn!=null)
{
try{
PreparedStatement update;
update=conn.prepareStatement(sql);
update.execute();
}
catch(SQLException e)
{
strExc=e.toString();
}
catch(Exception e)
{
strExc=e.toString();
}
}
else
{
strExc="Connection Lost!";
}
return(strExc); - }}//execute_sql
- ********************************************************************************************************
- 分析jsp頁面
頁面名稱:
fenye.jsp - 頁面代碼:
<%@ page errorPage="error1.jsp"%>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<!--//導入database_basic包下面的databaseBean類,別名是basicDB -->
<jsp:useBean id="basicDB" class="loan.databaseBean" scope="page"/>
<html>
<%
String sql;
ResultSet rs;
int id;
String reply,Exc;
Exc=basicDB.DBConnect();//建立連接,若成功,則返回Success!若失敗,則返回相應出錯信息
if(!Exc.equals("Success!"))
{
//basicDB.DBDisconnect();
throw new Exception(Exc);
}
int pageSize=3; //定義每頁顯示的數據條數
int currentPage=1; //當前頁(第一次顯示的肯定是第一頁啦!~),以後的“當前頁”由下面出現的頁面中的pages參數傳入
int allPage=-1;
String pages=request.getParameter("pages");//取得頁面中pages參數,此參數代表的頁面的就是要顯示的“當前頁面”
if(pages!=null) currentPage=Integer.valueOf(pages).intValue();//這是一個Integer型轉int型的例子,第一次執行這個頁面的時候,pages這個參數是null,currentPage=1;當再次執行這個頁面的時候,參數pages將被賦值,currentPage=pages的int值
sql="select * from teacher order by id desc";//這樣返回的結果集會採用desc降序排列,好處是,顯示在前面的是最新的信息
allPage=basicDB.getTotalPage(sql,pageSize);//得到總頁碼數
rs=basicDB.getPagedRs(sql,pageSize,currentPage);//得到當前頁面要顯示的結果集
%><body background="images/789.gif">
<table border="0" cellspacing="1" cellpadding="3" width="700" bgcolor="#ffffff">
<%
while(rs.next()){
id=rs.getInt("id");//得到數據庫(結果集)中id編號
%>
<tr bgcolor="#FF6600" style="color:white">
<td >姓名:<%=rs.getString("name")%></td>
<td >院系:<%=rs.getString("department")%></td>
<td >專業:<%=rs.getString("zhuanye")%></td>
<td >性別:<%=rs.getString("sex")%></td>
<td >電話:<%=rs.getString("tel")%></td>
</tr>
<tr bgcolor="#FFE3B9">
<td colspan="5"><FONT COLOR="#FF6600">備註:</FONT><BR><BR><%=rs.getString("remark")%> </td>
</tr>
<%}%>
<tr><td height="1"></td></tr>
<tr>
<td colspan="5"align=right bgcolor="#FF6600" style="color:white;">
現在是第<%=currentPage%>頁,
<%if(currentPage>1){%>
<!--如果不在第一頁,則顯示出“首頁”鏈接-->
<A HREF="fenye.jsp?pages=1">首頁</A>
<%}
for(int i=1;i<=allPage;i++)
{
//顯示出1、2、3、4……到最後一頁的鏈接
out.println("<a href=fenye.jsp?pages="+i+">"+i+"</a>");
}
%>
<%if(currentPage<allPage){%>
<!--如果不在最後一頁,則顯示出“末頁”鏈接-->
<A HREF="fenye.jsp?pages=<%=(allPage)%>">末頁</A>
<%}%></td>
</tr>
</table>
</body>
</html>
效果如圖: