用JDBC实现数据的分页显示

数据分页主要用到了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);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值