現代web系統中存在大量的數據,如果不分頁,這些數據將難以處理
分頁有利於頁面的展示,並且減輕服務器和數據庫的壓力。
分頁的種類
1.僞分頁,內存級分頁
查詢的是全部數據,但是隻展示一部分
2.真分頁,又稱爲物理分頁,或者叫組數據庫分頁
查詢和展示的都是部分數據
MySQL數據庫分頁
-- mysql數據庫分頁語句
-- 關鍵字limit 起始位置(offset) 查詢數量((pageSize)
-- 全量查詢
select * from student;
-- 每頁顯示5條
select *from student limit 0,5;
-- 第二頁顯示的內容
SELECT *from student limit 5,5;
Dao層代碼
package org.lanqiao.dao.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.lanqiao.bean.Student;
import org.lanqiao.dao.IStudentDao;
import org.lanqiao.util.DBUtil;
public class StudentDaoImpL implements IStudentDao{
@Override
public List<Student> getStuByPage(int currentPage, int pageSize) {
//建立連接
Connection conn=DBUtil.getConn();
String sql="select *from student limit ?,?";
Object[] objs= {(currentPage-1)*pageSize,pageSize};
ResultSet rs=DBUtil.excuteQuery(sql, objs);
List<Student> students=new ArrayList<>();
try {
while(rs.next()) {
int sid=rs.getInt("id");
String name=rs.getString("name");
String pass=rs.getString("pass");
String grade=rs.getString("grade");
int age=rs.getInt("age");
int teaId=rs.getInt("tea_id");
Student student=new Student(sid,name,pass,grade,age,teaId);
students.add(student);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return students;
}
}
分頁工具類Page.java
currentPage 當前頁
pageSize 每頁顯示的條數
offset 偏移量
totalCount 數據總條數
totalPage 數據總頁數
獲取總頁數的數據的總條數
-- 獲取總條數
SELECT COUNT(id) from student;
Dao層代碼
public int getStuCount() {
//建立連接
Connection conn=DBUtil.getConn();
String sql="select count(id) from student";
ResultSet rs=DBUtil.excuteQuery(sql, null);
int count=-1;
try {
if(rs.next()) {
count=rs.getInt(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}