java 调用用java写的oracle存储过程的相关问题

来源:互联网 发布:linux查看端口号 编辑:程序博客网 时间:2024/06/09 15:42

按照昨天的思维,今天总算是把用java调用oracle存储过程实现数据库备份这个功能实现了,但是为了给存储过程加入个返回值,这样还是出了比较大的问题,因为存储过程里面是调用java的函数实现逻辑的,但是怎么把java函数的返回值赋值给存储过程里面的变量,这是一个问题。相关代码在下面

java 代码如下

create or replace and compile java source named "cmd" as import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Oscmd extends Object {public static String oscmd(String cmd) throws InterruptedException {Runtime rt = Runtime.getRuntime();Process p = null;boolean shouldClose = false;try {// p = rt.exec("exp scott/tiger@orcl file=d:/Desktop/expdat.dmp");p = rt.exec(cmd);InputStreamReader isr = new InputStreamReader(p.getErrorStream());BufferedReader br = new BufferedReader(isr);String line = null;while ((line = br.readLine()) != null) {if (line.indexOf("错误") != -1) {shouldClose = true;System.out.println(line);break;}}} catch (IOException e) {shouldClose = true;}if (shouldClose) {p.destroy();return "fail";}int exitVal = p.waitFor();System.out.println(exitVal);return "success";}}

然后是存储过程的创建,按照如下创建函数的方法是能够创建成功的

create or replace
function oscmd1(cmd VARCHAR2 ) return VARCHAR2
as language java 
name 'Oscmd.oscmd(java.lang.String) return java.lang.String';

但是存储过程是不支持返回值的,于是Oscmd.oscmd(java.lang.String) return java.lang.String这样的一句话就会报错,怎样把函数的返回值赋值给存储过程,这里就要用存储过程的基本语法解决,可以看看这样的代码转成存储过程里的代码的实现

DECLARE
  CMD VARCHAR2(200);
  RE VARCHAR2(200);
BEGIN
  CMD := NULL;


  OSCMD(
    CMD => CMD,
    RE => RE
  );
  DBMS_OUTPUT.PUT_LINE('RE = ' || RE);
END;

虽然我最后是在存储过程里面调用oracle函数来实现的

create or replace
procedure oscmd(cmd in VARCHAR2 ,re out VARCHAR2) 
is
begin
select oscmd1(cmd) into re from dual;
end;

然后就是java里面怎么调用返回变量的存储过程的代码

 SessionFactory sessionFactory= hibernateTemplate.getSessionFactory();
 Session session =sessionFactory.openSession();  
 Connection connection = session.connection();
 CallableStatement proc = null;
 proc = connection.prepareCall("{Call oscmd(?,?)}"); 
 proc.setString(1, "exp scott/tiger@orcl file=d:/Desktop/expdat.dmp");    
 proc.registerOutParameter(2, Types.VARCHAR);
 proc.execute();
 String result = proc.getString(2);
 System.out.println(result);
 return null;   


这样就能大概完成我们所需的功能了

0 0