数据分页主要用到了resultSet的absolute()方法用来定位到某一行上去,其代码如下:
当我们需要定位到某一页的时候,或则是显示特定的某一页的时候,我们可以用如下的方法实现:
package com.ajliu.pageOperation;
import java.sql.*;
import com.ajliu.UtilTool.*;
import java.util.*;
public class PageTest {
public static void operation(){
System.out.println("===================================");
System.out.println("====this is the split operation====");
System.out.println("please input the number of the page");
}
public static void main(String args[]){
operation();
Connection conn=null;
Statement stm=null;
ResultSet rs=null;
try{
conn=ConnectTool.getConnection();
conn.setAutoCommit(false);
/*---设置可滚动可更新的结果集-*/
stm=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
/*--查出员工的ID号和姓名--*/
String sql="select empno,Ename from emp order by sal";
rs=stm.executeQuery(sql);
System.out.println(rs.getFetchSize());
Scanner scanner=new Scanner(System.in);
int i=scanner.nextInt();//每页显示多少行
int j=0;
rs.next();
do{
/*当前显示的行数是否达到了指定的行数*/
if(i==j){
j=0;
System.out.println("show the next page,please input the 'P'");//显示下一页
System.out.println("show the last page,please input the l ");//显示上一页
System.out.println("exit,please input the 'e'");
String a=scanner.next();
if(a.equals("l")){
int rowNum=rs.getRow()-2*(i+1);//获取上一页的起始下标
if(rowNum==0){ //判断是否是回到起始下标
rs.absolute(1);
System.out.println(rs.getInt(1)+"=="+rs.getString(2));
j=1;
}
else{
rs.absolute(rowNum);}//定位上一页的位置
continue;
}
if(a.equals("p")){
continue;
}
else{break;}
}
System.out.println(rs.getInt(1)+"=="+rs.getString(2));
j++;
}while(rs.next());
conn.commit();
}catch(Exception e){
e.printStackTrace();
try {
conn.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}finally{
ConnectTool.releasersc(rs, stm, conn);
}
}
}
}
当我们需要定位到某一页的时候,或则是显示特定的某一页的时候,我们可以用如下的方法实现:
/*
* 功能:分页显示所有给定的结果集
* 参数:rs代表要分页的结果集,pageNum代表的每页显示几条记录
* */
public static void pagefilter(ResultSet rs,int pageNum)throws Exception{
Scanner scanner=new Scanner(System.in);
int totalRow=rs.getFetchSize();//获取所查询的结果集的行数
int totalPage=0;
/*判断跟定的结果集是否可以刚好显示完,如果不能,则加上一页*/
if(totalRow%pageNum==0){
totalPage=totalRow/pageNum;
}
else{
totalPage=totalRow/pageNum+1;
}
do{
int recordNum=0;//该页已经显示了几条记录
System.out.println("exit,please input '100'");
System.out.println("please input the page you want to show:");
int number=scanner.nextInt();//显示第几页,
if(number==100){
break;
}
if(number<1||number>totalPage){
System.out.println("你输入的页面不正确!");
continue;
}
number=number-1;
rs.absolute(number*pageNum+1);//定位到当显示的页面
/*显示第几页的内容*/
while(recordNum!=pageNum){
System.out.println(rs.getInt(1)+"=="+rs.getString(2));
//判断下一个行是否有值
if(!rs.next()){
break;
} ;
recordNum++;
}
}while(true);
}