Oracle
 sql >> Base de données >  >> RDS >> Oracle

Comment passer la liste de java à la procédure Oracle ?

Convertissez vos listes en un tableau multidimensionnel et vous pourrez ensuite faire quelque chose comme :

Configuration d'Oracle :

CREATE TYPE stringlist AS TABLE OF VARCHAR2(100);
/

CREATE TYPE stringlist_list AS TABLE OF stringlist;
/

CREATE TYPE stringlist_list_list AS TABLE OF stringlist_list;
/

CREATE PROCEDURE load_list (
  in_list IN stringlist_list_list
)
AS
BEGIN
  NULL; -- Do something with the list
END;
/

Java :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.OracleCallableStatement;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;

public class TestDatabase2 {
  public static void main(String args[]){
    try{
      Class.forName("oracle.jdbc.OracleDriver");

      Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username","password");

      // Convert your lists to arrays using #toArray( T[] )

      String[] l1 = { "Math", "Physics" };
      String[] l2 = { "English", "Spanish" };
      String[] l3 = { "French", "German" };

      ArrayDescriptor des = ArrayDescriptor.createDescriptor("STRINGLIST_LIST_LIST", con);

      ARRAY school = new ARRAY( des, con, newString[][][]{
        new String[][]{ l1, l3 },
        new String[][]{ l2, l3 }
      } );

      CallableStatement st = con.prepareCall("{ call add_school( :school )}");

      // Passing an array to the procedure - 
      ((OracleCallableStatement) st).setARRAYAtName( "school", school );

      st.execute();
    } catch(ClassNotFoundException | SQLException e) {
      System.out.println(e);
    }
  }
}