下面是一个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) is begin 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
原文地址:http://flyingfish.blog.51cto.com/9580339/1584464