Thursday, October 01, 2009

Java Stored Procedures

Its been a very long time that I have been wanting to execute some java stored procedures in the oracle database. And today finally I got to learn how to do them. This link clearly explained how we can execute java programs in the database and how we can create database procedures to call the java programs. With the help of the above link i created a sample HelloWorld program to be executed on my 11g database.

Below is a simple HelloWorld program that i wrote in java.

public class HelloWorld {
public static void printHello(String name) {
System.out.println("Hello "+name);
}
}

using the below statement I compiled the above code in the database.

loadjava -u nreddy/nreddy -v -j -t HelloWorld.java

After that i create a package with the below specification and body.

create or replace package Hello_World is

procedure Print_Hello(name varchar2);

end Hello_World;
/

create or replace package body Hello_World is

procedure Print_Hello(name varchar2) as language java
name 'HelloWorld.printHello(java.lang.String)';

end Hello_World;
/

Then i set the serveroutput on and execute the below procedure.

exec dbms_java.set_output(2000);

call hello_world.print_hello('Nirmala');

SQL> call hello_world.print_hello('Nirmala');
Hello Nirmala

Call completed.

Isn't that pretty cool. I know its very basic but I am extremely delighted to know how to execute a java program in Oracle.

No comments: