赞
踩
在plsql里可以查看到这个实例有个表叫fenye:
首先下载ojdbc.jar ,提取码:iehb
随便建立一个java项目:
添加JUnit4,把ojdbc包导进来:
创建一个Cono测试类用于测试:
public class Cono { @Test public void t1() { //注册驱动 String driver = "oracle.jdbc.driver.OracleDriver"; //连接路径 jdbc:oracle:thin:@ip:数据库运行端口:数据库名 String url = "jdbc:oracle:thin:@111.231.228.126:1521:array"; //用户名 String username = "array"; //用户密码 String password = "916437"; try { Class.forName(driver); Connection con = DriverManager.getConnection(url,username,password); Statement sta = con.createStatement(); String sql="select * from fenye"; ResultSet rs=sta.executeQuery(sql); while(rs.next()) { System.out.println(rs.getObject(1)+","+rs.getObject(2)); } } catch (Exception e) { // TODO: handle exception } } }
/*startnum和endnum都是数值型传入参数,nn是游标型传出参数*/
create or replace procedure fenye_method(startnum number,endnum number,nn out sys_refcursor)
is
begin
open nn for
select id,name from
(select rownum r,e.* from fenye e where rownum<=endnum order by id)
where r>startnum;
end;
执行完然后刷新就在过程里看得到有个方法了:
然后在java测试类里写调用的方法:
@Test public void t2() { String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@111.231.228.126:1521:array"; String username = "array"; String password = "916437"; try { Class.forName(driver); Connection con = DriverManager.getConnection(url,username,password); CallableStatement fenye_method = con.prepareCall("{call fenye_method(?,?,?)}"); fenye_method.setInt(1, 0); fenye_method.setInt(2, 10); fenye_method.registerOutParameter(3, OracleTypes.CURSOR); fenye_method.execute(); ResultSet rs=((OracleCallableStatement)fenye_method).getCursor(3); while(rs.next()) { System.err.println(rs.getObject(1)+","+rs.getObject(2)); } System.out.println(); } catch (Exception e) { // TODO: handle exception } }
这就是java程序调用oracle分页的方法了。
此外为了方便,我们还可以封装一个调用分页的方法:
public void f(Integer start,Integer end) { String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@111.231.228.126:1521:array"; String username = "array"; String password = "916437"; try { Class.forName(driver); Connection con = DriverManager.getConnection(url,username,password); CallableStatement fenye_method = con.prepareCall("{call fenye_method(?,?,?)}"); fenye_method.setInt(1, start); fenye_method.setInt(2, end); fenye_method.registerOutParameter(3, OracleTypes.CURSOR); fenye_method.execute(); ResultSet rs=((OracleCallableStatement)fenye_method).getCursor(3); while(rs.next()) { System.err.println(rs.getObject(1)+","+rs.getObject(2)); } System.out.println(); } catch (Exception e) { // TODO: handle exception } }
执行测试类t3:
@Test
public void t3() {
f(0,10);
System.out.println("-------------");
f(10,20);
}
这些java方法都是没有返回值的,如果需要返回值,可以考虑新建一个pojo来接收从oracle数据库取出来的数据
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。