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>
*/
public class Pagination<T> {
// 当前页
private Integer nowPage;
// 页面要显示信息条数
private Integer pageSize;
// 根据页面显示的条数计算总页数
private Integer countPage;
// 根据传入的数据库查询数据库中的信息的条数
private Integer total;
// 向数据库查询时的开始的下标
private Integer startIndex;
// 向数据库查询时的查询条数
private Integer endIndex;
// 将查询到的数据存放到这里
private List<T> rows;
public Pagination(Integer nowPage, Integer pageSize, 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);
*/
}
// 根据提供的表名向数据库发送请求,计算指定数据表中的数据总条数
public Integer getCountSize(String tableName) {
int countRecord = 0;
String sql = "select count(*) as c from " + tableName;
Connection conn = 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);
}
return countRecord;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
public Integer getStartIndex() {
return startIndex;
}
public Integer getEndIndex() {
return endIndex;
}
public Integer getTotal() {
return total;
}
}