Java Stored Procedure in Oracle, Database Interaction - A Simple Java Class
(Page 2 of 5 )
One should remember that Java stored procedures are still Java classes, but stored as Oracle schema objects. They will be made accessible to Oracle SQL and PL/SQL through call specifications. Call specifications, as we will see, are simply PL/SQL declarations that 'wrap' methods of Java stored in the database. Call specifications, in other words, work as mediators (or interfaces).
Another important issue to consider is that Java methods must be “public” and they must be “static” if they are to be used as stored procedures inside an Oracle database.
JDeveloper is the product from Oracle, which seems to be a famous IDE for Java developers who need Oracle based Java stored procedures to develop and deploy very easily. You can write, compile, and even unit test your Java code before moving it into the Oracle database. But in this article, you work with a simple notepad by saving the following code as “Employee.java”.
The following listing displays a simple Java class called “Employee”. For now, it contains a single method to “insert” an employee record into the database.
import java.sql.*;
import oracle.jdbc.*;
public class Employee {
//Add an employee to the database.
public static void addEmp(int empno, String ename,
float sal, int deptno) {
System.out.println("Creating new employee...");
try {
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
String sql =
"INSERT INTO emp " +
"(empno,ename,sal,deptno) " +
"VALUES(?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,empno);
pstmt.setString(2,ename);
pstmt.setFloat(3,sal);
pstmt.setInt(4,deptno);
pstmt.executeUpdate();
pstmt.close();
}
catch(SQLException e) {
System.err.println("ERROR! Adding Employee: "
+ e.getMessage());
}
}
}
There is nothing much new in the above program. In this method, the database connection URL is "jdbc:default:connection:". When writing Java that will execute inside the Oracle database, you can take advantage of a special server-side JDBC driver. This driver uses the user's default connection (which is also called a context connection) and provides the fastest access to the database.
Next: Getting Java Classes into Oracle Database >>
More Java Articles
More By Jagadish Chaterjee