Download - Work With Java Oracle
-
8/14/2019 Work With Java Oracle
1/2
How can I work with Java in the Database? Administration Tips
Copyright Howard Rogers 2001 1/11/2001 Page 1 of 2
How can I work with Java in the Database?
You can start by using Java Stored Procedures. Here, Ill show you how you can make Java
do the absolute classic job of updating the salary field for a specified employee in the EMP
table. Its a useless thing to do in real life: Java is a complex language, and makes doing
very simple things (like update emp set sal=) incredibly hard work and youd be a mugto do it in real life. But Javas complexities also mean that doing very complex things are
much easier than trying to do it with PL/SQL or SQL alone.
Im not taking you down the very-complex-made-easy path (partly because I think well
both get lost!). But at least this simple example will give you an idea of how to start to
get Java working for you.
First, copy this script exactly into a text editor (notepad or vi, for example), and save it in
a file called Test.java (and yes, theres a capital T and a lower case j there, and both
are significant). Save it in your Oracle_Home directory (it doesnt have to be saved there,but it makes things a bit easier later on).
import java.sql.*;public class Test {public static void updateSal(int empid, int salary) {try{ Connection connection = DriverManager.getConnection("jdbc:oracle:kprb:");Statement statement = connection.createStatement();int norows = statement.executeUpdate("UPDATE emp SET sal = "+salary+"WHERE empno = "+empid);connection.commit();}catch (SQLException e) {System.out.println(e);}}}A word to the wise: that statement is case sensitive like you wouldnt believe! When I
inadvertently tried it with its line 7 reading CreateStatement(); the second stage
produced errors complaining that CreateStatement was not a method it was aware of.
Quite right too: it knows about createStatement with the lower case c! If you cant
manage to type all that in exactly, therefore, youll find a working, tested version on the
Scripts page of this website.
Second, in your Oracle_Home directory (wherever that might be) type the following
command:
loadjava u scott/tiger@SID r Test.javaThe SID there should obviously be replaced with the actual name of the Instance in
which you wish to run this Java Stored Procedure. That must relate to an entry in your
tnsnames.ora file.
-
8/14/2019 Work With Java Oracle
2/2