package jdbcDay03; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class TestPage { public static void main(String[] args) { // getResult(20,10); // getPage(10,5); //每页是10条。,,第5页 int page=0; System.out.println("你输入的页码是:"); Scanner ss=new Scanner(System.in); page=ss.nextInt(); getpageSimple(10,page); // System.out.println(getTotalNumber()); } public static void getResult(int m,int n){ //输出指定从m到n的记录 String sql="select id ,user_id,login_time,logout_time,rn "+ "from (select id,user_id,login_time,logout_time,rownum rn from mytemp where rownum<?)" +"where rn>=?"; try { Connection conn=ConnectionUtils.openConnection(); PreparedStatement pstmt=conn.prepareStatement(sql); pstmt.setInt(1,m); pstmt.setInt(2, n); ResultSet rs=pstmt.executeQuery(); while(rs.next()){ String line=rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(5); System.out.println(line); } pstmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void getPage(int pageSize,int page){ int from=(page-1)*pageSize+1; int to=from+pageSize; String sql="select id ,user_id,login_time,logout_time,rn "+ "from (select id,user_id,login_time,logout_time,rownum rn from mytemp where rownum<=?)" +"where rn>=?"; try { Connection conn=ConnectionUtils.openConnection(); PreparedStatement pstmt=conn.prepareStatement(sql); pstmt.setInt(1, to); pstmt.setInt(2, from); ResultSet rs=pstmt.executeQuery(); while(rs.next()){ String line=rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(5); System.out.println(line); } pstmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void getpageSimple(int pageSize,int page){ int totalPage=0; //总共有多少页数 int totalNumber=getTotalNumber(); if(totalNumber%pageSize==0){ totalPage=totalNumber/pageSize; }else{ totalPage=totalNumber/pageSize+1; } if(page>totalPage){ page=totalPage; }else if(page<1){ page=1; } int from =(page-1)*pageSize+1; int to=from +pageSize; getResult(to,from); } public static int getTotalNumber(){ //获得mytemp中共有多少条记录 String sql="select Count(*) num from mytemp"; int n=-1; try { Connection conn=ConnectionUtils.openConnection(); Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery(sql); rs.next(); n=rs.getInt("num"); } catch (SQLException e) { e.printStackTrace(); } return n; } }