网页中常用分页效果代码
程序员文章站
2022-04-28 12:00:16
...
package com.page.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.entor.jdbc.DBUtil;
public class Page {
public static void main(String[] args) {
showPage(1);
}
public static void showPage(int page) {
int pageSize = 5; //页大小
int total = getTotal(); //总记录数
//总页数
int totalPage = total%pageSize==0?total%pageSize :total%pageSize +1;
System.out.println("总页数:" + totalPage);
// 计算起始行号和结束行号
int start = pageSize * (page-1)+1;
int end = start + pageSize;
//分页的sql
String sql = "select * from " +
" (select rownum rn, t.* from " +
" (select * from emp) t " +
" ) tt" +
" where tt.rn>=? and tt.rn<?";
Connection conn = DBUtil.getConnection();
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, start);
ps.setInt(2, end);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("empno") + "\t" + rs.getString("ename"));
}
}catch (Exception e) {
e.printStackTrace();
}
}
//获取总记录数
private static int getTotal() {
Connection conn = DBUtil.getConnection();
PreparedStatement ps;
int total = 0;
try {
ps = conn.prepareStatement("select count(*) from emp");
ResultSet rs = ps.executeQuery();
if(rs.next()) {
total = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return total;
}
}
代码中所引用到的DBUtil类是我将java连接数据库的代码封装而成,避免多次写重复的语句,代码请看下一篇文章