sql >> Base de Datos >  >> RDS >> Oracle

Obtener salida de dbms_output.get_lines usando JDBC

También he escrito sobre este tema aquí. Aquí hay un fragmento que ilustra cómo se puede hacer esto:

try (CallableStatement call = c.prepareCall(
    "declare "
  + "  num integer := 1000;" // Adapt this as needed
  + "begin "

  // You have to enable buffering any server output that you may want to fetch
  + "  dbms_output.enable();"

  // This might as well be a call to third-party stored procedures, etc., whose
  // output you want to capture
  + "  dbms_output.put_line('abc');"
  + "  dbms_output.put_line('hello');"
  + "  dbms_output.put_line('so cool');"

  // This is again your call here to capture the output up until now.
  // The below fetching the PL/SQL TABLE type into a SQL cursor works with Oracle 12c.
  // In an 11g version, you'd need an auxiliary SQL TABLE type
  + "  dbms_output.get_lines(?, num);"

  // Don't forget this or the buffer will overflow eventually
  + "  dbms_output.disable();"
  + "end;"
)) {
    call.registerOutParameter(1, Types.ARRAY, "DBMSOUTPUT_LINESARRAY");
    call.execute();

    Array array = null;
    try {
        array = call.getArray(1);
        System.out.println(Arrays.asList((Object[]) array.getArray()));
    }
    finally {
        if (array != null)
            array.free();
    }
}

Lo anterior imprimirá:

[abc, hello, so cool, null]

Tenga en cuenta que ENABLE / DISABLE La configuración es una configuración de conexión amplia, por lo que también puede hacer esto en varias declaraciones JDBC:

try (Connection c = DriverManager.getConnection(url, properties);
     Statement s = c.createStatement()) {

    try {
        s.executeUpdate("begin dbms_output.enable(); end;");
        s.executeUpdate("begin dbms_output.put_line('abc'); end;");
        s.executeUpdate("begin dbms_output.put_line('hello'); end;");
        s.executeUpdate("begin dbms_output.put_line('so cool'); end;");

        try (CallableStatement call = c.prepareCall(
            "declare "
          + "  num integer := 1000;"
          + "begin "
          + "  dbms_output.get_lines(?, num);"
          + "end;"
        )) {
            call.registerOutParameter(1, Types.ARRAY, "DBMSOUTPUT_LINESARRAY");
            call.execute();

            Array array = null;
            try {
                array = call.getArray(1);
                System.out.println(Arrays.asList((Object[]) array.getArray()));
            }
            finally {
                if (array != null)
                    array.free();
            }
        }
    }
    finally {
        s.executeUpdate("begin dbms_output.disable(); end;");
    }
}

Tenga en cuenta también que esto obtendrá un tamaño fijo de 1000 líneas como máximo. Es posible que deba realizar un bucle en PL/SQL o sondear la base de datos si desea más líneas.

Una nota sobre cómo llamar a DBMS_OUTPUT.GET_LINE en cambio

Anteriormente, había una respuesta ahora eliminada que sugería llamadas individuales a DBMS_OUTPUT.GET_LINE en cambio, que devuelve una línea a la vez. He evaluado el enfoque comparándolo con DBMS_OUTPUT.GET_LINES , y las diferencias son drásticas:hasta un factor 30 veces más lento cuando se llama desde JDBC (incluso si no hay una gran diferencia cuando se llama a los procedimientos desde PL/SQL).

Entonces, el enfoque de transferencia masiva de datos usando DBMS_OUTPUT.GET_LINES definitivamente vale la pena Aquí hay un enlace al punto de referencia:

https://blog.jooq.org/2017/12/18/the-cost-of-jdbc-server-roundtrips/