Java (2014) implements code bitsCN.com for mysql database paging
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
*/Public class Pagination
{// Private Integer nowPage on the current page; // The number of information entries to be displayed on the page: private Integer pageSize; // calculate the total number of private Integer countPage pages based on the number of entries displayed on the page; // The number of items in the database queried by the input database is private Integer total; // The subscript private Integer startIndex at the beginning of the query to the database; // The number of queries to the database: private Integer endIndex; // store the queried data here: private List
Rows; public Pagination (Integer nowPage, Integer pageSize, String tableName) {// assign this. nowPage = nowPage; this. pageSize = pageSize; // determines whether the current page is legal if (this. nowPage <1) {this. nowPage = 1;} // send a query to the database to query the total number of data in the specified table. total = this. getCountSize (tableName); // calculate the total number of pages 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 ("nowPage ==========" + this. nowPage); // calculate the initial record subscript and the number of entries to be displayed on each page 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 + "====== start and end of pagenation ========" + this. endIndex + "=============================== total number of pages" + countPage ); * /} // send a request to the database based on the provided table name, and calculate the total number of data entries in the specified data table. 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.exe cuteQuery (); if (rs. next () {countRecord = rs. getInt ("c") ;}} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {JdbcUtil. release (rs, pstmt);} return countRecord;} public List
GetRows () {return rows;} public void setRows (List
Rows) {this. rows = rows;} public Integer getStartIndex () {return startIndex;} public Integer getEndIndex () {return endIndex;} public Integer getTotal () {return total ;}}
BitsCN.com