Java编程琐事(7)——封装JDBC分页

一、编写一个接口从ResultSet继承:

package com.solid.test;

import java.sql.ResultSet;

import java.sql.SQLException;

public interface Pageable extends ResultSet {

//返回总页数

int getPageCount();

//返回当前页的记录条数

int getPageRowsCount();

//返回分页大小

int getPageSize();

//转到指定页

void gotoPage(int page);

//设置分页大小

void setPageSize(int pageSize);

//返回总记录行数

int getRowsCount();

//转到当前页的第一条记录

void pageFirst() throws SQLException;

//转到当前页的最后一条记录

void pageLast() throws SQLException;

//返回当前页号

int getCurrentPageNo();

}

二、编写实现接口的方法:

public class PageableResultSet implements Pageable {

protected ResultSet rs=null;

//每页行数

protected int rowsCount;

//分页大小

protected int pageSize;

//当前页号

protected int currentPageNo;

protected String command = "";

//构造方法

public PageableResultSet(ResultSet rs) throws java.sql.SQLException {

if(rs==null) throw new SQLException("given ResultSet is NULL","user");

rs.last();

rowsCount=rs.getRow();

rs.beforeFirst();

this.rs=rs;

}

//返回当前页号

public int getCurrentPageNo() {

return currentPageNo;

}

//返回总页数

public int getPageCount() {

// TODO Auto-generated method stub

if(rowsCount == 0) return 0;

if(pageSize == 0) return 1;

double tmpD = (double)rowsCount/pageSize;

int tmpI = (int)tmpD;

if(tmpD > tmpI) tmpI++;

return tmpI;

}

//返回当前页的记录条数

public int getPageRowsCount() {

if(pageSize == 0) return rowsCount;

if(getRowsCount() == 0) return 0;

if(currentPageNo != getPageCount()) return pageSize;

return rowsCount-(getPageCount()-1)*pageSize;

}

//返回分页大小

public int getPageSize() {

return pageSize;

}

//返回每页行数

public int getRowsCount() {

return rowsCount;

}

//跳转到第几页

public void gotoPage(int page) {

if(rs == null) return;

if(page < 1) page = 1;

if(page > getPageCount()) page = getPageCount();

int row = (page - 1) * pageSize + 1;

try {

rs.absolute(row);

currentPageNo = page;

} catch (SQLException e) {

e.printStackTrace();

}

}

//跳转到首页

public void pageFirst() throws SQLException {

int row=(currentPageNo - 1) * pageSize + 1;

rs.absolute(row);

}

//跳转到最后一页

public void pageLast() throws SQLException {

int row=(currentPageNo - 1) * pageSize + getPageRowsCount();

rs.absolute(row);

}

//设置分页大小

public void setPageSize(int pageSize) {

if(pageSize >= 0){

this.pageSize = pageSize;

currentPageNo = 1;

}

}

}

三、JSP页面中分页操作:

<table width="100%" border="0" cellpadding=0 cellspacing=0 align<

你可能感兴趣的:(java,sql,编程,jsp,jdbc)