In class yesterday, we learned how to make our system page query, here we will use the limit of SQL.
1. First, let's create a new java file named PageBean.
package com.zhongruan.bean;
import java.util.List;
public class PageBean<T> {
private int currentPage;
private int pageSize;
private List<T> musics;
private int totalCount;
private int totalPage;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public List<T> getMusics() {
return musics;
}
public void setMusics(List<T> musics) {
this.musics = musics;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
@Override
public String toString() {
return "PageBean{" +
"currentPage=" + currentPage +
", pageSize=" + pageSize +
", musics=" + musics +
", totalCount=" + totalCount +
", totalPage=" + totalPage +
'}';
}
}
Here are some variables we will use.
We put some query pagination code in MusicService:
if (j == 1) {
System.out.println("-------欢迎进入音乐管理系统-------");
System.out.println("\t1.查询音乐\t2.添加音乐\t3.修改音乐\t4.删除音乐\t5.返回上一层");
int a = input.nextInt();
switch (a) {
case 1:
int count = musicDao.getCount();
pageBean.setTotalCount(count);
double ceil = Math.ceil(count / 5.0);//12 5 2.4 3 2 2 2.1 3
int totalPage= (int) ceil;
pageBean.setTotalPage(totalPage);
System.out.println("请问你要查询第几页:我们一共有"+totalPage+"页");
int i=input.nextInt();
List<Music> music1 = getMusic(i, totalPage, musicDao);
System.out.println("下一步还要做什么:\t1.上一页 \t2.下一页 \t3.退出");
int i1 = input.nextInt();
switch (i1){
case 1:
if(i==1){
getMusic(1, totalPage, musicDao);
}else{
getMusic(i-1, totalPage, musicDao);
}
break;
Connect to the database and SQL statement:
public int getCount() throws SQLException{
Connection connection=DBUtil.getconnection();
connection.prepareStatement("select count (*) from music");
PreparedStatement statement=null;
ResultSet resultSet=statement.executeQuery();
int count=0;
while (resultSet.next()){
count = resultSet.getInt(1);
}
DBUtil.closeAll(resultSet,statement,connection);
return count;
}