Saturday, April 16, 2011

Call External Program from Database using Triggers

This is certainly possible either you call xp_cmdshell, which allows you to invoke an external program, or use sp_oacreate and sp_oamethod, which allow you to manipulate COM objects this is the case with MsSQL Server, in oracle we can use LoadJava with functions but i think there is some limitations with MySQL, i don't know if somebody know this pls let me know. 

Some where it was mentioned that it is not a better idea or recommended to call trigger. A trigger holds open atransaction in your database. Any delay in releasing that transaction or any failure to release it can cause blocking of other processes. Also, if your external program accesses the database in any way then there is the
possibility of causing an undetectable deadlock.

It is better to poll the database to see if that change has happened and then invoke your code as required. That way transaction performance is unaffected.

i will suggest create a temp table, a trigger on the master table to dump the changes to the temp table and now poll temp table from any external java program or anything, so this way performance on the existing transaction/master table is not going to impact.

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