java实现对数据库的分页

来源:互联网 发布:证书查询系统源码 编辑:程序博客网 时间:2024/05/23 11:59
package util;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
 
/**
 * @author Hongyu
 *
 * @param <T>
 */
publicclass Pagination<T> {
    // 当前页
    privateIntegernowPage;
    // 页面要显示信息条数
    privateIntegerpageSize;
    // 根据页面显示的条数计算总页数
    privateIntegercountPage;
    // 根据传入的数据库查询数据库中的信息的条数
    privateIntegertotal;
    // 向数据库查询时的开始的下标
    privateIntegerstartIndex;
    // 向数据库查询时的查询条数
    privateIntegerendIndex;
 
 
    // 将查询到的数据存放到这里
    private List<T> rows;
 
    publicPagination(IntegernowPage, IntegerpageSize, String tableName) {
        // 赋值
        this.nowPage = nowPage;
        this.pageSize = pageSize;
 
        // 判断当前页是否合法
        if (this.nowPage < 1) {
            this.nowPage = 1;
        }
 
        // 向数据库发送查询,查询出指定表格的数据的总数
        this.total = this.getCountSize(tableName);
        // 计算总页数
        this.countPage = this.total % this.pageSize == 0 ? this.total
                / this.pageSize : this.total / this.pageSize + 1;
 
        if (this.nowPage > this.countPage) {
            this.nowPage = this.countPage;
        }
 
        //System.out.println("pagenation中的nowPage=========="+ this.nowPage);
        // 计算出开始的记录下标,和每页要显示的条数
 
        if (this.nowPage == 0) {
            this.startIndex = this.nowPage * this.pageSize;
            this.endIndex = this.pageSize;
        }else{
            this.startIndex = (this.nowPage - 1) * this.pageSize;
            this.endIndex = this.pageSize;
        }
 
        /*System.out.println(this.startIndex + "======pagenation中的开始和结束========"
                + this.endIndex+"====================总页数"+countPage);
*/
    }
 
    // 根据提供的表名向数据库发送请求,计算指定数据表中的数据总条数
    publicInteger getCountSize(String tableName) {
        intcountRecord = 0;
        String sql = "select count(*) as c from " + tableName;
        Connectionconn = JdbcUtil.getConn();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                countRecord = rs.getInt("c");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.release(rs, pstmt);
        }
        returncountRecord;
    }
 
    publicList<T> getRows() {
        returnrows;
    }
 
    publicvoid setRows(List<T> rows) {
        this.rows= rows;
    }
 
    publicInteger getStartIndex() {
        returnstartIndex;
    }
 
    publicInteger getEndIndex() {
        returnendIndex;
    }
 
    publicInteger getTotal() {
        returntotal;
    }
     
 
 
}
0 0