在Java中调用PLSQL函数返回Boolean

时间:2018-05-16 17:33:05

标签: java jdbc

我在java中调用 PLSQL 函数。该函数返回布尔值,然后检查以确定函数是否已成功完成。如果返回false,则检查out参数以获取错误消息。完成此任务的正确方法是什么?

我的班级看起来像这样。

package com.jdbcjava.examples;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;


public class JDBCCallOracleFunction {

   private static final String DB_DRIVER="jdbc:oracle:thin:@//localhost:1521/orcl";
   private static final String DB_USER="hr";
   private static final String DB_PASSWD="hr";


   public static void main(String[] args){

       callFunctionOUTparameter();

   }



   private static void callFunctionOUTparameter(){

       try{
            Connection dbconnection =getDBConnection();
            CallableStatement mystmt=dbconnection.prepareCall("{?= call get_details(?,?,?,?,?) }");
            mystmt.registerOutParameter(1, Types.BOOLEAN);  // Would this work?
            mystmt.setInt(2, 100);
            mystmt.registerOutParameter(3, Types.VARCHAR);
            mystmt.registerOutParameter(4, Types.VARCHAR);
            mystmt.registerOutParameter(5, Types.DATE);
            mystmt.registerOutParameter(6, Types.VARCHAR);

            mystmt.execute();

            System.out.println(mystmt.getBoolean(1)); // Would this work?
            System.out.println(mystmt.getString(2));
            System.out.println();


       }
        catch(SQLException e){
           e.printStackTrace();
       }catch(Exception e){
           e.printStackTrace();    
       }         
   }


   private static Connection getDBConnection() throws Exception{

       Connection dbconnection= DriverManager.getConnection(DB_DRIVER, DB_USER,DB_PASSWD);       
       return dbconnection;
   }

}

添加功能

CREATE OR REPLACE FUNCTION get_details(
I_emp_id IN NUMBER,
O_first_name OUT VARCHAR2,
O_last_name OUT VARCHAR2,
O_hire_date OUT DATE,
O_error_message OUT varchar2) return BOOLEAN
IS
CURSOR c_emp_info IS
select first_name,
       last_name,
       hire_date
  from employees 
 where employee_id = I_emp_id;

 begin

    open c_emp_info;
    fetch c_emp_info into  O_first_name,
                           O_last_name,
                           O_hire_date;


    close c_emp_info;

    return true;

 exception
    when others then 
      O_error_message := substr(sqlerrm,1,100);
      return false;
 end;
 /

0 个答案:

没有答案