`

转Oracle分页查询

阅读更多

1.Oralce的分页查询

分页查询:可以简化表复杂度,让一张很大的表,分成很多块,不要一次性全部显示成一整块;方便阅览

 

可以将下列语句当成一个模版使用select * from (select t1.*,rownum rn from emp t1 where rownum < 8) where rn > 3;

 

定义一个包,包里面有游标变量类型:(记住游标变量是不能在包中或包体中声明的比如 mycursor sys_refcursor这是不允许的)

 

 

Sql代码   收藏代码
  1. create or replace package mypage  
  2. is  
  3. type cursor_emp is ref cursor;  
  4. end mypage;  
 

接着写存储过程,来实现分页的业务逻辑

   下面定义了六个变量, 三个输入参数(表名,第几页,一页显示几行数据),三个输出变量(表中数据总共的行数,表总共分了几页,游标变量(用来指明你需要查询的记录)).

 

 

Sql代码   收藏代码
  1. --pageCount 显示第几页  
  2. --pageSize 一页显示的数据  
  3. create or replace procedure emp_pro(tableName varchar2,pageCount number,pageSize number,  
  4. allSize out number,allPage out number,mycursor out mypage.cursor_emp)  
  5. is  
  6. Sql_s varchar2(1000);  
  7. Sql_count varchar2(1000);  
  8. startSize number:=pageCount*pageSize-pageSize+1;  
  9. endSize number:=pageCount*pageSize;  
  10. begin  
  11.   
  12.   Sql_s:='select * from  
  13.     (select t1.*,rownum rn from '||tableName||' t1 where rownum <= '||endSize||'where rn >= '||startSize;  
  14.     open mycursor for Sql_s;  
  15.    Sql_count:='select count(*) from emp';  
  16.    execute immediate Sql_count into allSize;  
  17.    if mod(allSize,pageSize)=0 then  
  18.            allPage:=allSize/pageSize;  
  19.       else  
  20.            allPage:=allSize/pageSize+1;  
  21.    end if;  
  22. end;  

 

    我们来分析下面的语句

Sql_s:='select * from(select t1.*,rownum rn from '||tableName||' t1 where rownum <= '||endSize||') where rn >= '||startSize; open mycursor for Sql_s;

 

    其实在PL/SQL编程中,可以把你需要写的SQL语句给一个字符变量,当执行存储过程的时候,oracle自动会辨认出来,

   execute immediate SQL语句 into 变量

   这一句的意思是:立即执行给定的SQL语句,把返回的结果给变量

 

  JAVA调用存储过程:

 

 

Java代码   收藏代码
  1. try  
  2. {  
  3.     Class.forName("oracle.jdbc.driver.OracleDriver");  
  4.     Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:Class","scott","admin");  
  5.     CallableStatement call = con.prepareCall("{call emp_pro(?,?,?,?,?,?)}");  
  6.     call.setString(1"EMP");  
  7.     call.setInt(25);  
  8.     call.setInt(34);  
  9.     //注册属性值  
  10.     call.registerOutParameter(4, OracleTypes.INTEGER);  
  11.     call.registerOutParameter(5, OracleTypes.INTEGER);  
  12.     call.registerOutParameter(6, OracleTypes.CURSOR);  
  13.     call.execute();  
  14.     int ALLSIZE = call.getInt(4);  
  15.     int ALLPAGE = call.getInt(5);  
  16.     System.out.println("记录数: "+ALLSIZE);  
  17.     System.out.println("总页数: "+ALLPAGE);  
  18.     ResultSet rs = (ResultSet)call.getObject(6);  
  19.     while(rs.next())  
  20.     {  
  21.         System.out.println("EMPNO="+rs.getInt(1)+"  "+"ENAME="+rs.getString(2)+  
  22.                 " "+"SAL="+rs.getInt(6));  
  23.     }  
  24. }  
  25. catch(Exception e)  
  26. {  
  27.     e.printStackTrace();  
  28. }  
 

转自:http://aazham.iteye.com/blog/1167341

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics