Can we call a Java Stored Proc from a PL/SQL stored Proc?

Hello!
Do you know how to call a Java Stored Proc from a PL/SQL stored Proc? is it possible? Could you give me an exemple?
If yes, in that java stored proc, can we do a call to an EJB running in a remote iAS ?
Thank you!

For the java stored proc called from pl/sql, the example above that uses dynamic sql should word :
CREATE OR REPLACE PACKAGE MyPackage AS
TYPE Ref_Cursor_t IS REF CURSOR;
FUNCTION get_good_ids RETURN VARCHAR2 ;
FUNCTION get_plsql_table_A RETURN Ref_Cursor_t;
END MyPackage;
CREATE OR REPLACE PACKAGE BODY MyPackage AS
FUNCTION get_good_ids RETURN VARCHAR2
AS LANGUAGE JAVA
NAME 'MyServer.getGoodIds() return java.lang.String';
FUNCTION get_plsql_table_A RETURN Ref_Cursor_t
IS table_cursor Ref_Cursor_t;
good_ids VARCHAR2(100);
BEGIN
good_ids := get_good_ids();
OPEN table_cursor FOR 'SELECT id, name FROM TableA WHERE id IN ( ' | | good_ids | | ')';
RETURN table_cursor;
END;
END MyPackage;
public class MyServer{
public static String getGoodIds() throws SQLException {
return "1, 3, 6 ";
null

Similar Messages

  • How can I call a java object from Web dynpro ABAP application?

    I made Web dynpro ABAP application and posted it to SAP EP.
    For certain business purpose, we need to call external 3rd party java object using 3rd party's java api in Web dynpro application.
    Is there anybody who experienced this kind of java interface issue?
    I know Web dynpro Java environment can fully support this kind of requirement. but regarding Web dynpro ABAP, I couldn't find any clue for this.
    Any comment or suggestion would be greatly appreciated.
    Thanks,
    Raymond, ABAP Consultant

    if you have jco configured, then you can make calls to java api from ABAP .
    check out this weblog.
    /people/gregor.wolf3/blog/2004/08/26/setup-and-test-sap-java-connector-outbound-connection
    Raja

  • Size limitation that can be passed to Java stored procedure

    Hello!
    I enjoy using Oracle8i these days. But I have some questions
    about Java stored procedure. I want to pass the XML data to Java
    stored procedure as IN parameter. But I got some errors when the
    data size is long. Is there any limitation in the data size that
    can be passed to Java stored procedure?
    Would you please help me ?
    This message is long, but would you please read my message?
    Contents
    1. Outline : I write what I want to do and the error message I
    got
    2. About the data size boundary: I write about the boundary
    size. I found that it depend on which calling sequence I use.
    3. The source code of the Java stored procedure
    4. The source code of the Java code that call the Java stored
    procedure
    5. The call spec
    6. Environment
    1.Outline
    I want to pass the XML data to Java stored procedure. But I got
    some errors when the data size is long. The error message I got
    is below.
    [ Error messages and stack trace ]
    java.sql.SQLException: ORA-01460: unimplemented or unreasonable
    conversion reque
    sted
    java.sql.SQLException: ORA-01460: unimplemented or unreasonable
    conversion reque
    sted
    at oracle.jdbc.ttc7.TTIoer.processError(Compiled Code)
    at oracle.jdbc.ttc7.Oall7.receive(Compiled Code)
    at oracle.jdbc.ttc7.TTC7Protocol.doOall7(Compiled Code)
    at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch
    (TTC7Protocol.java:721
    at oracle.jdbc.driver.OracleStatement.doExecuteOther
    (Compiled Code)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithBatch
    (Compiled Code)
    at oracle.jdbc.driver.OracleStatement.doExecute(Compiled
    Code)
    at
    oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(Compiled
    Code
    at
    oracle.jdbc.driver.OraclePreparedStatement.executeUpdate
    (OraclePrepar
    edStatement.java:256)
    at oracle.jdbc.driver.OraclePreparedStatement.execute
    (OraclePreparedStat
    ement.java:273)
    at javaSp.javaSpTestMain.sample_test
    (javaSpTestMain.java:37)
    at javaSp.javaSpTestMain.main(javaSpTestMain.java:72)
    2. About the data size boundary
    I don|ft know the boundary that I got errors exactly, but I
    found that the boundary will be changed if I use |gprepareCall("
    CALL insertData(?)");|h or |gprepareCall ("begin insertData
    (?); end ;")|h.
    When I use |gprepareCall(" CALL insertData(?)".
    The data size 3931 byte --- No Error
    The data size 4045 byte --- Error
    Whne I use prepareCall ("begin insertData(?); end ;")
    The data size 32612 byte --No Error
    The data size 32692 byte --- Error
    3. The source code of the Java stored procedure
    public class javaSpBytesSample {
    public javaSpBytesSample() {
    public static int insertData( byte[] xmlDataBytes ) throws
    SQLException{
    int oraCode =0;
    String xmlData = new String(xmlDataBytes);
    try{
    Connection l_connection; //Database Connection Object
    //parse XML Data
    dits_parser dp = new dits_parser(xmlData);
    //Get data num
    int datanum = dp.getElementNum("name");
    //insesrt the data
    PreparedStatement l_stmt;
    for( int i = 0; i < datanum; i++ ){
    l_stmt = l_connection.prepareStatement("INSERT INTO test
    " +
    "(LPID, NAME, SEX) " +
    "values(?, ?, ?)");
    l_stmt.setString(1,"LIPD_null");
    l_stmt.setString(2,dp.getElemntValueByTagName("name",i));
    l_stmt.setString(3,dp.getElemntValueByTagName("sex",i));
    l_stmt.execute();
    l_stmt.close(); //Close the Statement
    l_stmt = l_connection.prepareStatement("COMMIT"); //
    Commit the changes
    l_stmt.execute();
    l_stmt.close(); //Close the Statement l_stmt.execute
    (); // Execute the Statement
    catch(SQLException e ){
    System.out.println(e.toString());
    return(e.getErrorCode());
    return(oraCode);
    4. The source code of the Java code that call the Java stored
    procedure
    public static void sample_test(int num) {
    //make data
    Patient p = new Patient();
    byte[] xmlData = p.generateXMLData(num);
    try{
    // Load the Oracle JDBC driver
    DriverManager.registerDriver(new
    oracle.jdbc.driver.OracleDriver());
    Connection m_connection = DriverManager.getConnection
    ("jdbc:oracle:thin:@max:1521:test",
    "testuser", "testuser");
    CallableStatement l_stmt =
    // m_connection.prepareCall(" CALL insertData(?)");
    m_connection.prepareCall("begin insertData(?); end
    l_stmt.setBytes(1,xmlData);
    l_stmt.execute();
    l_stmt.close();
    System.out.println("SUCCESS to insert data");
    catch(SQLException e ){
    System.out.println( e.toString());
    e.printStackTrace();
    5. The call spec
    CREATE OR REPLACE PROCEDURE insertData( xmlData IN LONG RAW)
    AS
    LANGUAGE JAVA NAME 'javaSp.javaSpBytesSample.insertData(byte[])';
    6. Environment
    OS: Windows NT 4.0 SP3
    RDBMS: Oracle 8i Enterprise Edition Release 8.1.5.0.0 for
    Windows NT
    JDBC Driver: Oracle JDBC Drivers 8.1.5.0.0.
    JVM: Java1.1.6_Borland ( The test program that call Java stored
    procedure run on this Java VM)
    null

    Iam passing an array of objects from Java to the C
    file. The total size of data that Iam sending is
    around 1GB. I have to load this data into the Shared
    memory after getting it in my C file. Iam working on
    HP-UX (64-bit). Everything works fine for around 400MB
    of data. When I try to send around 500MB of data, the
    disk utilization becomes 100%, so does my memory
    utilization and I get a "Not enough space" when I try
    to access shared memory. I have allocated nearly 2.5GB
    in my SHMMAX variable. Also, I have around 45GB of
    disk free. The JVM heap size is also at 2048MB. Where did you get the 400/500 number from? Is that the size of the file?
    What do you do with the data? Are you doing nothing but copying it byte for byte into shared memory?
    If yes then a simple test is to write a C application that does the same thing. If it has problems then it means you have an environment problem.
    If no then you are probably increasing the size of the data by creating a structure to hold it. How much overhead does that add to the size of the data?

  • Out of memory error when calling a java stored procedure multiple times

    Trying to run a PL/SQL loop calling a java stored procedure, I get the following error:
    "ORA-04030: out of process memory when trying to allocate 262188 byte callheap,ioc_allocate free)"
    (with some other error lines).
    The stored procedure does two major things:
    1) Open a socket to communicate with a server, of which it queries some data.
    2) Use JDBC (with the default DB connection it has, as a stored procedure) to write the results to a table.
    All socket connections, statements, etc. are properly closed and all memory should be garbage collected between each call.
    Can anyone offer an explanation or additional checks to make? I'm quite sure the code isn't causing the problem, since I've tried running it as a stand alone application (outside of Oracle) and didn't have any problems.
    Thanks.

    Hi,
    Verify that the database parameters are set correctly.
    EA

  • Calling a java web service from R/3 6.0

    hi experts,
    can anyone please tell me how to call a java web service from R/3 6.0?
    i found some answers to this question but all those were for 6.4 or 6.2 but not for 6.0.
    i want to generate a outbound flow from ERP system. so please tell me something about web service in that context.
    Thanks in advance,
    Sagar.

    Hi!!!
    I would do this scenario as a synchronous one:
    [SAP R/3][ABAP proxy objects] <-> [XI]<->[SOAP Adapter]<--->[external java app]
    In your ABAP transaction you will have to execute ABAP proxy method to send a message to XI. If it's not your transaction, you can use user-exit.
    BTW, I have an experience with XI 2.0, not with 3.0, so I used a XI 2.0 terminology.
    Regards,
    Andrzej Filusz

  • How can I create a java.awt.Image from ...

    Hi all,
    How can I create a java.awt.Image from a drawing on a JPanel?
    Thanks.

    JPanel p;
    BufferedImage image =
        new BufferedImage(p.getWidth(), p.getHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    p.paint(g);
    g.dispose();

  • How can I call a SAPME web service from MII such as PlaceFutureHold?

    Dears,
    How can I call a SAPME web service from MII such as PlaceFutureHold?
    By using MII, I would like to develop some logic to check some values which query from SAPME database, if the value is out of spec, it needs to send a emal to inform user ans also hold the SFC.
    Thanks!

    With Web service action block you can view all ME available services
    in I.E
    https://sapme:5000/manufacturing-services/ProductionServiceService?wsdl  you could see your FutureHold service
    To do that in MII, you need Web Service action block. Have you work with MII transaction before?
    (saw your post in MII)

  • Can we call a Java Map in Message  Map

    Hello,
    Can we call a Java Map in Message  Map
    Thanks and Regards
    Hemant

    Hello Vijay,
    I think this is your code:
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.AbstractTrace;
    import com.sap.aii.mapping.api.StreamTransformationConstants;
    import java.util.Map;
    import java.io.*;
    public class PayloadToXMLField1 implements StreamTransformation {
        String strXML = new String();
       //Declare the XML tag for your XML message
       String StartXMLTag = "<DocumentBody>";
       String EndXMLTag = "</DocumentBody>";
       //String StartXMLTag1 = "<Code>";
       //String EndXMLTag1 = "</Code>";
        AbstractTrace trace;
        private Map param = null;
        public void setParameter(Map param) {
            this.param = param;
        public void execute(InputStream in, OutputStream out) {
            trace =
                (AbstractTrace) param.get(
                    StreamTransformationConstants.MAPPING_TRACE);
            trace.addInfo("Process Started");
            try {
                StringBuffer strbuffer = new StringBuffer();
                byte[] b = new byte[4096];
                for (int n;(n = in.read(b)) != -1;) {
                    strbuffer.append(new String(b, 0, n));
                strXML = strbuffer.toString();
            } catch (Exception e) {
                System.out.println("Exception Occurred");
            String outputPayload =
                StartXMLTag
             + "<![CDATA["
             + strXML
             + "]]>"
             + EndXMLTag;
            try {
                out.write(outputPayload.getBytes());
             trace.addInfo("Process Completed");;
            } catch (Exception e) {
                trace.addInfo("Process Terminated: Error in writing out payload");;
    I need this code to be converted in UDF if Java map cannot be called in Message Map.
    Can anyone help me how to write UDF for the same java map.
    Thanks and Regards
    Hemant

  • How can I call a java class from within my program?

    I was wondering if there's a platform independent way to call a java class from my program.

    Here's my scenario. I'm working on a platform independent, feature rich, object-oriented command prompt program. The way I'm designing it is that users can drop classes they write into my bin directory and gain access to the class through my program. For example, they drop a class named Network.class in the bin directory. They would type Network network at my command prompt and gain access to all the methods available in that class. They can then type system.echo network.ipaddress() at my prompt and get the system's ip address. I have it designed that there's a server running in the background and the clients connect to my port. Once connected the end-user can enter their user name and password and gain access to the system. When they type a command they actually call another java program which connects to my server using a seperate thread. They can then communicate back and forth. I have it set that everything has a process id and it's used to keep track of who called what program. Once the program is done it disconnects and closes. Rather than getting into the nitty gritty (I didn't want to get into heavy detail, I know how everything will work) I'm really interested in finding out how I can call a java program from my program. I don't want it to be part of the app in any way.

  • How can I call a pop up window from a java class ?

    Hi,
    I am developing a web app. I would like to call a windoz pop up from a java class.
    How can i do that ?
    Thanks

    user504072 wrote:
    It was possible to do it in ASP .NET even from the server side with the method Page.ClientScript. What do you think what Page.ClientScript stands for?
    I's an encapsulation for the JavaScript code required and hides the separation between frontend and backend. There was a reason why so many developers stick to the MVC-pattern wich ist violated here.
    I did not know it is not possible to do the same thing in Java.I'ts not a task of the backend to layout the user interaction GUI.
    bye
    TPD

  • Can I call a Java program from a SQL Server Trigger?

    Hello,
    I want to encrypt some data in a database column in SQL Server. Today I am using java code to encrypt the value and store it in the database using JDBC.
    Now I want to use a VB client to store the encrypted value in the SQL Server DB. Since the encryption is handled by a java class, can I write a trigger in SQL Server that while inserting the raw data, calls the java class for encrypting the value and then inserts the encrypted value into the column?
    In general, is it possible to call a java class from a SQL Server trigger?
    Thanks
    Bipin

    Here are 3 examples of code for insert, update and delete:
    CREATE TRIGGER [PLI_INSERT_TRIGGER] ON [dbo].[PLI]
    FOR INSERT
    AS
    Declare @cmd sysname, @code sysname, @list sysname
         Select @code = PLI_K_COD, @list = PLI_K_LISTINO from inserted
         Set @cmd = 'java mirrorDb.Copy PLI INSERT ' + @code + ' ' + @list
         EXEC master..xp_cmdshell @cmd
    CREATE TRIGGER [PLI_UPDATE_TRIGGER] ON [dbo].[PLI]
    FOR UPDATE
    AS
    Declare @cmd sysname, @code sysname, @list sysname
         Select @code = PLI_K_COD, @list = PLI_K_LISTINO from inserted
         Set @cmd = 'java mirrorDb.Copy PLI UPDATE ' + @code + ' ' + @list
         EXEC master..xp_cmdshell @cmd
    CREATE TRIGGER [PLI_DELETE_TRIGGER] ON [dbo].[PLI]
    FOR DELETE
    AS
    Declare @cmd sysname, @code sysname, @list sysname
         Select @code = PLI_K_COD, @list = PLI_K_LISTINO from deleted
         Set @cmd = 'java mirrorDb.Copy PLI DELETE ' + @code + ' ' + @list
         EXEC master..xp_cmdshell @cmd
    you must go "sql server entreprise manager" right click on the table you want to add triggers and select: all activities, manage triggers.
    You have 3 examples: for an insert, for an update and for a delete
    ON [dbo].[PLI] specify the table on which you want to setup trigger.
    FOR DELETE, INSERT, UPDATE specify the event.
    The Declare statement create the variables in which I want to put some values to pass to the java program, for example which table, which event, which key fields.
    the "Select @code = PLI_K_COD, @list = PLI_K_LISTINO from inserted" set the variables with the value of the columns of the table I am interested to read from my java program, for example the variable @code receive the value of the column pli_k_kod (is the key) of the table PLI.
    The "Set @cmd = 'java mirrorDb.Copy PLI DELETE ' + @code + ' ' + @list " prepared the variable @cmd with the java command followed by the package.classname and parameters.
    The EXEC launch the command to the operating system.
    Daniele

  • System calls through Java stored Proc

    Hi,
    Aim: Execute host command from pl/sql thru java stored proc.
    1. Created a java class to take system command that could be executed.
    2. It runs fine when the class file is executed.
    3. when the java file is loaded to database to access it as java stored proc, for any valid and invalid system commands it is giving out 'PL/SQL successfully completed.
    Results were not seen.
    4. Java source file.
    import java.io.*;
    import java.lang.*;
    public class Util extends Object
    public static int RunThis(String[] args) {
    Runtime rt = Runtime.getRuntime();
    int rc = -1;
    String s = null;
    try
    Process p = rt.exec(args);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
    System.out.println(s);
    System.exit(0);
    catch (Exception e){
    e.printStackTrace();
    rc = -1;
    finally {
    return rc;
    public static void main(String[] args){
    Util.RunThis(args);
    public static String exec(String args){
              Util.RunThis(args);
              return "Srini it is successful";
    5. When ran from host prompt (unix),
    executed successfully,
    $ /opt/java1.3.1/bin/java Util /usr/bin/ls -l
    Here is the standard output of the command:
    total 30862
    -rwxrwxrwx 1 xyz develope 1348218 Jan 2 17:47 02Jan03-2.zip
    -rw-r----- 1 xyz develope 21864 Jul 9 2002 109-60_2_modified7.sql
    -rw-r----- 1 xyz develope 44934 Jul 9 2002 109-60_2_modified8.sql
    Here is the standard error of the command (if any):
    xyz@xxxxx:abcd:/home/xyz
    $
    6. loadjava,
    $ loadjava -user username/password Util.java
    7. Create proc,
    SQL> create procedure echo_input(s1 varchar2) as language java name 'Util.main(java.lang.String[])';
    2 /
    Procedure created.
    8. Execute proc.
    SQL> exec echo_input('/usr/bin/ls -l');
    PL/SQL procedure successfully completed.
    SQL> exec echo_input('/home/o_report/reports/rcli_ASCT &');
    PL/SQL procedure successfully completed.
    SQL> set serverout on
    SQL> exec echo_input('/home/o_report/reports/rcli_ASCT');
    PL/SQL procedure successfully completed.
    SQL> exec echo_input('ddsafafasf');
    PL/SQL procedure successfully completed.
    TIA,
    Srini.

    Hi Srini,
    This is just a suggestion, but try entering the following commands (in your SQL*Plus session) before executing your stored procedure:
    set serveroutput on size 1000000
    exec dbms_java.set_output(1000000)Hope this helps.
    Good Luck,
    Avi.

  • Can we call a java method from python

    Hi, Can we invoke a java application from python. If yes, can any of you post a sample python script. Also please specify any links if you find useful for this. I do not want to use either Jython or any others for this. I would like to do it particularly from Python.
    Thanks.

    For Perl there was a module that allows to access java classes there might be a one for python too do a goole search

  • Can I Call method on one JVM from another through a dll?

    Let me explain.
    I have this java jar file that I can only have one instance of running at any given time. I'm using a shared data segment in a dll to store a bool indicating whether the program is already running or not. If it's already running, I have to not run the second instance and give focus to the current running instance.
    The jar file calls a native method "canInstantiate()" on a dll to see if there's already an app running. If there isn't, the env and obj are stored in the shared data segment of the dll and we return true. If there is already an instance of the program running, I want canInstantiate call a function on the current instance of the jar (like a callback) to tell it to request focus. It's not working. Can someone tell me if my code is right?
    The .h file
    #include "stdafx.h"
    #include <jni.h>
    #include "CardServer.h"
    #pragma data_seg("SHARED") // Begin the shared data segment.
    static volatile bool instanceExists = false;
    static JavaVM *theJavaVM = NULL;
    static JNIEnv* theJavaEnv= NULL;
    static jobject instanceObject = NULL;
    static jmethodID mid = NULL;
    static jclass cls = NULL;
    #pragma data_seg()
    #pragma comment(linker, "/section:SHARED,RWS")
    jdouble canInstantiate(JNIEnv *env, jobject obj);
    jdouble instantiate(JNIEnv *env, jobject obj);
    jdouble uninstantiate(JNIEnv *env, jobject obj);
    void grabFocus();
    </code>
    The .cpp file:
    <code>
    #include "MyFunctions.h"
    #include <string.h>
    #include <stdlib.h>
    #include "stdafx.h"
    #include <iostream.h>
    jdouble canInstantiate(JNIEnv *env, jobject obj)
    printf("In canInstantiate!!");
    if (!instanceExists)
    printf("No instance exists!!");
    return (jdouble)0.0;
    else
    printf("An instance already exists!!");
    grabFocus();
    return (jdouble)1.0;
    jdouble instantiate(JNIEnv *env, jobject obj)
    printf("**In CPP: Instantiate!!\n");
    cout << "At start, env is: " << env << endl;
    cout << "At start, obj is: " << obj << endl;
    if (instanceExists == false)
    instanceExists = true;
    theJavaEnv = env;
    instanceObject = obj;
    theJavaEnv->GetJavaVM(&theJavaVM);
    cls = (theJavaEnv)->FindClass("TheMainClassOfTheJar");
    if (cls == 0) {
    fprintf(stderr, "Can't find Prog class\n");
    exit(1);
    mid = (theJavaEnv)->GetMethodID(cls, "grabFocusInJava", "(I)I");
    if (mid == 0) {
    fprintf(stderr, "Can't find grabFocusInJava\n");
    exit(1);
    printf("About to call grabFocusInJava\n");
    grabFocus();
    printf("CPP: After the grab focus command in instantiate!!\n");
    cout << "At end, env is: " << env << endl;
    cout << "At end, obj is: " << obj << endl;
    return 0.0;
    else
    printf("CPP: Finished Instantiate!!\n");
    return 1.0;
    jdouble uninstantiate(JNIEnv *env, jobject obj)
    printf("CPP: In uninstantiate!!\n");
    if (instanceExists == true)
    instanceExists = false;
    theJavaVM = NULL;
    instanceObject = NULL;
    printf("CPP: Finishing uninstantiate!!\n");
    return 0.0;
    else
    printf("CPP: Finishing uninstantiate!!\n");
    return 1.0;
    void grabFocus()
    printf("In CPP::GrabFocus!!\n");
    instanceObject = theJavaEnv->NewGlobalRef(instanceObject);
    cls = (theJavaEnv)->FindClass("CardFormatter");
    if (cls == 0) {
    fprintf(stderr, "Can't find Prog class\n");
    exit(1);
    printf("Got the cls id again!!\n");
    if (cls == 0)
    printf("IT'S INVALID!!\n");
    mid = (theJavaEnv)->GetMethodID(cls, "grabFocusInJava", "(I)I");
    if (mid == 0) {
    fprintf(stderr, "Can't find grabFocusInJava\n");
    exit(1);
    theJavaEnv->CallIntMethod(instanceObject, mid, 2);
    printf("Called grabFocusInJava\n");
    </code>
    thanks in advance

    Can I Call method on one JVM from another through a dll
    ...The rest of your question merely expands on your title.
    And the answer to that question is no.
    When you call a method you are executing a "thread of execution." A thread of execution exists only in a single process. It can not exist in another process.
    If the dll is doing some interesting things then you could call a method that sets a flag. Data can move between instances. But you would then have to have a thread in that different process monitoring that flag. And sharing data in a dll is not a normal process, so it would have to be coded appropriately.
    If all you want to do is set the current focus to the existing application, then that can be done with existing windows functionality. You don't need to do anything special in your dll. You can probably search these forums to find the exact code. If not there are countless examples in windows repositories (like MSDN) on how to do that.

  • SQLException: Cursor is closed while calling a java stored procedure

    Hi,
    I got the following error when trying to read from a cursor of a java stored procedure:
    java.sql.SQLException: Cursor is closed
    The java procedure is stored in the database and wrapped by a sql call. Then another java class executes the sql call.
    The stored procedure looks like this:
    import java.io.Reader; import java.security.MessageDigest; import java.sql.*; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import oracle.jdbc.OracleCallableStatement; import oracle.jdbc.OracleConnection; public class test { static Connection conn = null; static String username = null; static String password = null; static Integer userid  = null; public static void main(String args[]) throws Exception {     username = "keller";     password = "945435";     login(username, password); }       public static String login(String in_username, String in_password) {     String access = null;     String password = null;         try {             DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());  // Non OracleVM             System.out.print("Verbindung wird initialisiert... ");             conn =         //DriverManager.getConnection("jdbc:default:connection:");           //conn.setAutoCommit(false);             DriverManager.getConnection("jdbc:oracle:thin:@[...]:1521:[...]","[...]","[...]");             System.out.println("OK");                         System.out.print("Logindaten werden ueberprueft... ");             String sql = "SELECT matrikelnr, password FROM student WHERE name = ?";             PreparedStatement pstmt = conn.prepareStatement(sql);             pstmt.setString(1, in_username);             ResultSet rset = pstmt.executeQuery();             while (rset.next())             {             userid = rset.getInt(1);                 password = rset.getString(2);             }             access = "student";                         pstmt = conn.prepareStatement(sql);             if (password == null) {             sql = "SELECT dozentnr, password FROM dozent WHERE name = ?";                 pstmt = conn.prepareStatement(sql);                 pstmt.setString(1, in_username);                 rset = pstmt.executeQuery();                 while (rset.next())                 {             userid = rset.getInt(1);                     password = rset.getString(2);                                     }                 pstmt = conn.prepareStatement(sql);                 if (password == null) {                   throw new SQLException("User nicht gefunden!");                 }                 access = "dozent";             }             //rset.close(); // Resultset schließen             //pstmt.close(); // Statement schließen                         // MD5 Hash vergleichen             MessageDigest md5 = MessageDigest.getInstance("MD5");             md5.reset();             md5.update(in_password.getBytes());             byte[] result = md5.digest();             StringBuffer hexString = new StringBuffer();             for (int i=0; i<result.length; i++) {               if(result[i] <= 15 && result[i] >= 0){                 hexString.append("0");               }               hexString.append(Integer.toHexString(0xFF & result));
    if (password != null) {
    if (password.equals(hexString.toString())) {
    System.out.println("OK");
    } else {
    throw new Exception("Falsches Passwort!");
    catch(SQLException e) {
    System.err.println("SQL Fehler!");
    System.err.println(e.getMessage());
    catch(Exception e) {
    System.err.println("Fehler!");
    System.err.println(e.getMessage());
    return access;
    public static void getLeistungsschein(int matrikelnr, ResultSet[] rout)
    ResultSet rs = null;
    try
    System.out.print("Berechtigung ueberpruefen... ");
    if (userid != matrikelnr)
    throw new Exception("Zugriff verweigert, keine Berechtigung!");
    int mnr = matrikelnr;
    ((OracleConnection)conn).setCreateStatementAsRefCursor(true);
    PreparedStatement ps = conn.prepareStatement("select bezeichnung, note from klausur inner join leistungsschein on klausur.KLAUSURNR=leistungsschein.KLAUSURNR where matrikelnr= ?");
    ps.setInt(1, mnr);
    rs = (ResultSet)ps.executeQuery();
    rout[0]= rs;
    catch(SQLException e) {
    System.err.println("Fehler!");
    System.err.println(e.getMessage());
    catch(Exception e) {
    System.err.println("Fehler!");
    System.err.println(e.getMessage());
    The sql call:
    create or replace
    procedure pgetleistungsschein(matrikelnr in number, cur OUT refcurpkg.refcur_t) is
    language java name 'Klausurverwaltung.getLeistungsschein(int, java.sql.ResultSet[])';
    And finally the wrapper is called by another java programm, see this:
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.List;
    import oracle.jdbc.OracleCallableStatement;
    import oracle.jdbc.OracleResultSet;
    import oracle.jdbc.OracleTypes;
    public class cursortest {
    public static void main(String[] args) {
    try{
    //-- Oracle Treiber laden
    Class.forName( "oracle.jdbc.driver.OracleDriver" );
    Connection c = DriverManager.getConnection( "jdbc:oracle:thin:@sligo.fh-trier.de:1521:ubuntu", "dbsem_java","javajava");
    CallableStatement stmt = null;
    ResultSet rs1 = null;
    int matrnr = 945098;
    // Call PLSQL Stored Procedure
    stmt = (CallableStatement)c.prepareCall("{ call ? := getklausuren(?) }");
    stmt.setInt(2, matrnr);
    // 2nd parameter is OUT paremeter
    stmt.registerOutParameter(1, OracleTypes.CURSOR);
    // Execute the callable statement
    stmt.execute();
    //Cursor in ResultSet einlesen
    rs1 = ((OracleCallableStatement)stmt).getCursor(1);
    ResultSetMetaData rsmd = rs1.getMetaData();
    int anzSpalten = rsmd.getColumnCount();
    List<String[]> zeilen = new ArrayList<String[]>();
    while(rs1.next())
    String[] zeile = new String[anzSpalten];
    for (int i=1; i<=anzSpalten; i++)
    zeile[i-1]=rs1.getString(i);
    zeilen.add(zeile);
    String[][] array_angeb_klaus = (String[][])zeilen.toArray(new String[zeilen.size()][anzSpalten]);
    //**** ENDE
    rs1.close();
    stmt.close();
    //c.close();
    catch (SQLException e){
    System.out.println(e);
    catch (ClassNotFoundException f){
    System.out.println(f);

    On top of what jschell says, this just looks wrong in terms of how Oracle's internal Java works as well.
    [Have a look here |http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jdbc/refcur/index.html] (unless things have changed significantly over the past few years for Oracle Java).
    Is the db you are querying a different one to the one this Java is stored in?

Maybe you are looking for

  • Microsoft written application connectin to Database

    My application is written in C++ using Microsoft Visual Studio. How would I connect to database & retrieve information (insert/update/...)?

  • Lumia 1020 Freezes, Battery Heating Up, OS Crashes...

    Hi there everyone, this is my first post here, I hope I can get some help from you guys regarding my problem with my lovely Lumia 1020. 10 days ago, I received my Lumia 1020 ( it was a gift from a friend from Norway), I live in Iraq. So warranty isn'

  • Long text in bapi

    Hi I am trying to save a long text for material. to do this, I have to  fill a table of type bapi_mltx. If I insert one line all works correctluy, but if I try to insert more than one line, other lines are ignored and I can see only the first seem to

  • Missing files, images, pages, updates lost - watercolor template

    I am having a great time with the watercolor theme in the latest version of iWeb '08! A few weeks ago I spent over an hour updating my site, and published it. I quit iWeb, and then reopened it. All my changes were there! two weeks later. I open the d

  • Read Sequentially and Calculate

    Hello, I am running into the following situation I am trying to handle in Crystal Reports and am looking for input... Datasource1:  orders Datasource2:  unit of measure conversion formulas In Datasource1 the order quantities are in a specific unit of