標籤:java oracle 常式 執行預存程序
下面是一個java串連Oracle 執行一個沒有傳回值的預存程序的小常式。
package com.test;import java.sql.*;public class procedure { public static void main(String[] args) { Connection ct=null; CallableStatement cs=null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); ct=DriverManager.getConnection("jdbc:oracle:thin:@10.8.2.73:1521:orcl", "scott","123456"); cs=ct.prepareCall("{call pro_book(?,?,?)}"); cs.setInt(1, 10001); cs.setString(2, "華爾街之狼"); cs.setString(3, "中信出版社"); cs.execute(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally{ try { cs.close(); ct.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
下面是java執行一個有傳回值的預存程序的小程式。
package com.test;import java.sql.*;public class procedure {public static void main(String[] args) {Connection ct=null;CallableStatement cs=null;try {Class.forName("oracle.jdbc.driver.OracleDriver");ct=DriverManager.getConnection("jdbc:oracle:thin:@10.8.2.73:1521:orcl","scott","123456");cs=ct.prepareCall("{call pro_book_getname(?,?)}");cs.setInt(1, 10001);cs.registerOutParameter(2, oracle.jdbc.OracleTypes.VARCHAR);cs.execute();String name=cs.getString(2);System.out.println(name);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally{try {cs.close();ct.close();} catch (SQLException e) {e.printStackTrace();}}}}
一個取得一個集合的java程式:
首先先寫一個oracle包,定義一個cursor類型,PL/SQL如下:
create package pack_cursor is type type_cursor is ref cursor;end; /
再寫一個預存程序:
create or replace procedure pro_emp_cursor(no in number,cur out pack_cursor.type_cursor) isbegin open cur for select * from emp where deptno=no; end; /
java程式碼如下:
package com.test;import java.sql.*;public class procedure {public static void main(String[] args) {Connection ct=null;CallableStatement cs=null;try {Class.forName("oracle.jdbc.driver.OracleDriver");ct=DriverManager.getConnection("jdbc:oracle:thin:@10.8.2.73:1521:orcl","scott","123456");cs=ct.prepareCall("{call pro_emp_cursor(?,?)}");cs.setInt(1, 10);cs.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);cs.execute();ResultSet rs=(ResultSet)cs.getObject(2);while(rs.next()){System.out.println("EMPNO:"+rs.getInt(1)+" NAME:"+rs.getString(2)+" JOB:"+rs.getString(3));}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally{try {cs.close();ct.close();} catch (SQLException e) {e.printStackTrace();}}}}
本文出自 “飛魚技術” 部落格,請務必保留此出處http://flyingfish.blog.51cto.com/9580339/1584464
java串連oracle執行預存程序小程式