Saturday, April 16, 2011

Calling Java Methods in Oracle Database

With loadjava utility we can call java methods from the oracle database.

public class Hello
{
  public static String world()
  {
    return "Hello world";
  }
}
Save the file as a Hello.java file
Compile it using the standard Java compiler (it is better to compile it with oracle's own compiler)

Error while calling function if the class is not loaded successfully.
ORA-29541: Class MYTEST.Hello could not be resolved.

Try Loading the class on the server using the loadjava tool. You must specify the user name and password. Run the loadjava tool as follows.

D:\oracle\ora92\jdk\bin>
loadjava -resolve -verbose -user mytestuser/mytestpasswd "Hello.class"

arguments: '-resolve' '-verbose' '-user' 'mytestuser/mytestpasswd' 'Hello.class'
creating : class Hello
loading  : class Hello
resolving: class Hello

the above stmts shows it is successfully loaded.

In SQL*Plus, connect to the database and define a top-level call specification for Hello.world() as follows:

SQL> CREATE OR REPLACE FUNCTION helloworld RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'Hello.world () return java.lang.String';
     /
Function created

Call the stored procedure, as follows:

SQL> VARIABLE myString VARCHAR2(20);
SQL> CALL helloworld() INTO :myString;
Call completed.
SQL> PRINT myString

MYSTRING
---------------------------------------
Hello world

No comments:

Post a Comment