分类: 系统运维
2009-08-18 10:14:41
public interface Pageable extends java.sql.ResultSet{
int getPageCount(); //返回总页数
int getPageRowsCount(); //返回当前页的记录条数
int getPageSize(); //返回分页大小
void gotoPage(int page); //转到指定页
void setPageSize(int pageSize); //设置分页大小
int getRowsCount(); //返回总记录数
void pageFirst() throws java.sql.SQLException; //转到当前页第一条记录 抛出java.sql.SQLException异常
void pageLast() throws java.sql.SQLException; //转到当前页最后一条记录 抛出java.sql.SQLException异常
int getCurPage(); //返回当前页号
}
public class PageableResultSet2 implements Pageable {
protected java.sql.ResultSet rs=null;
protected int rowsCount;
protected int pageSize;
protected int curPage;
protected String command = "";
}
public boolean next() throws SQLException {
return rs.next();
}
public String getString(String columnName) throws SQLException { //这里是为了增加一些出错信息的内容便于调试
try {
return rs.getString(columnName);
}
catch (SQLException e) {
throw new SQLException (e.toString()+" columnName="
+columnName+" SQL="+this.getCommand());
}
}
public int getCurPage() {
return curPage;
}
public int getPageCount() { //calculate PageCount 计算页数
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(curPage!=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);
curPage = page;
}catch (java.sql.SQLException e) {
}
}
public void pageFirst() throws java.sql.SQLException {
int row=(curPage-1)*pageSize+1;
rs.absolute(row);
}
public void pageLast() throws java.sql.SQLException {
int row=(curPage-1)*pageSize+getPageRowsCount();
rs.absolute(row);
}
public void setPageSize(int pageSize) {
if(pageSize>=0){
this.pageSize=pageSize;
curPage=1;
}
}
public PageableResultSet2(java.sql.ResultSet rs) throws java.sql.SQLException { //PageableResultSet2的构造方法
if(rs==null) throw new SQLException("given ResultSet is NULL","user");
rs.last();
rowsCount=rs.getRow();
rs.beforeFirst();
this.rs=rs;
}
/**Pageable的使用方法
因为Pageable接口继承自ResultSet,所以在使用方法上与ResultSet一致,尤其是在不需要分页功能的时候,可以直接当成ResultSet使用。
而在需要分页时,只需要简单的setPageSize, gotoPage,即可。
PreparedStatement pstmt=null;
Pageable rs=null;
……//构造SQL,并准备一个pstmt.
rs=new PageableResultSet2(pstmt.executeQuery());//构造一个Pageable
rs.setPageSize(20);//每页20个记录
rs.gotoPage(2);//跳转到第2页
for(int i=0; i
……//继续处理
}
*/