`
tanlan
  • 浏览: 202040 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Oracle中的分页存储过程

阅读更多

1.创建测试表

create table Account(
    cardId char(20) primary key,  --帐号
    name char(20) not null,         --姓名
        money numeric(20,2)         --存款
);

 2.录入测试数据

insert into Account values('0001','张三',1000);
insert into Account values('0002','李四',2000);
insert into Account values('0003','王五',3000);
insert into Account values('0004','钱六',4000);

 3,编写一个视图以简化存储过程的编写与调用写法

create or replace view v_page 
as
select rownum rn,t.* from Account t;

 4,编写存储过程(省略了查询条件)

create or replace procedure P_Pagination(
       page  int,--第几页
       perPageCount int ,--每页几条记录
       totalPage out int,--总页数
       pageResultSet out SYS_REFCURSOR --当前页查询出来的结果集 
)
as
   totalCount int;--总记录数
   pageSql varchar(2000); --查询某页结果的SQL语句
begin
  select count(1) into totalCount from Account;  --查询总记录数
  totalPage := ceil( totalCount / perPageCount);   --算出总页数
  pageSql := 'select * from v_page u 
    where rn between '||(page-1)||'*'||perPageCount||'+1 and '||(page*perPageCount);
   open pageResultSet for pageSql;
end P_Pagination;

 5,在PL/SQL中调用该存储过程

declare 
   totalaPage int;  --总页数
   pageResult  SYS_REFCURSOR; --存放结果的变量
   account v_page%rowtype;
 begin
    P_Pagination(1,2,totalaPage,pageResult);
    dbms_output.put_line('总共'||totalaPage||'页');
    fetch pageResult into account;
   while pageResult%found loop
      dbms_output.put_line(account.cardid||','||account.name||','||account.money);
      fetch pageResult into account;
    end loop;
   close pageResult;
end;

 6,使用JDBC调用的代码片段

public static void main(String[] args) throws SQLException {
	Connection conn = ConnectionManage.getConnection();
	CallableStatement cs = conn.prepareCall("call P_Pagination(?,?,?,?)");
	cs.setInt(1, 1);
	cs.setInt(2, 3);
	cs.registerOutParameter(3, Types.INTEGER);
	cs.registerOutParameter(4, oracle.jdbc.OracleTypes.CURSOR);
	cs.execute();
	int totalPage = cs.getInt(3);
	System.out.println("共有" + totalPage + "页");
	ResultSet rs = (ResultSet) cs.getObject(4);
	while (rs.next()) {
		System.out.println(rs.getString("cardid")+","+rs.getString("name") +"," + rs.getString("money"));
	}
}
 
3
3
分享到:
评论
1 楼 njliukang 2013-08-24  
谭BOSS,连JDBC那块你用代理写写撒

相关推荐

Global site tag (gtag.js) - Google Analytics