12. There is a stored procedure that returns a value - list form (result set)

A stored procedure with a return value (list [result set]) is the most commonly used
because the oracle stored procedure has no return value, all its return values ​​are replaced by out parameters, and the list is no exception, but because it is a collection, it cannot be With general parameters, you must use package.

Case: Write a process, enter the department number, and return all employee information in the department

1) Build a package. As follows:
SQL> create or replace package testpackage as
  2 type test_cursor is ref cursor;
  3 end testpackage;
  4 /
Package created


2) Create a stored procedure. As follows:

SQL> --2. Create a stored procedure
SQL> create or replace procedure sun_pro13
  2 (sunNo in number, p_cursor out testpackage.test_cursor) is
  3 begin
  4 open p_cursor for select * from emp where deptno=sunNo;
  5 end;
  6 /
Procedure created

//It should be noted that the cursor cannot be closed, otherwise it cannot be called

in java. 3) How to call it in java?


public class Test1 {
        public static void main(String[] args) {
            Connection ct = null;
            CallableStatement cs = null;
            try {
                //1. Load driver
                Class.forName("oracle.jdbc.driver.OracleDriver");
                ct = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");
               
               
                //See how to call a stored procedure with a return value (list form [result set])
                //1. Create CallableStatement
                cs = ct.prepareCall("{call sun_pro13(?,?)}");
                //2. Give? Assignment
                cs.setInt(1, 10);
                cs.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
               

                cs.execute();
               
                //Get the result set
                ResultSet rs = (ResultSet) cs.getObject(2);
                       
                while(rs.next()){
                    System.out.println("Department number:"+rs.getInt(1 )+'\t'+rs.getString(2));
                }
               
            } catch (Exception e) {
                e.printStackTrace();
            }
            finally{
                //Close each open resource
                try {
                    cs.close();
                    ct.close ();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
}



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327002357&siteId=291194637