Writing The Java Class
Writing The Java Class
The beauty of this first step is that it really has little to do with the Oracle database.
You simply develop your Java classes using your favorite IDE, such as Oracle's
JDeveloper. Java methods must be public and they must be static if they are to be
used as stored procedures.
You can write, compile, and even unit test your Java code before moving it into the
Oracle database. In fact, for all but trivial applications, this is the preferred method
because it will allow you to take advantage of your IDE's features, such as debugging
and code generation. If you would prefer to compile your Java classes with Oracle's
JVM, the loadjava utility, discussed later, can do this for you.
The following listing displays a simple Java class called EmpManager. For now, it
contains a single method to insert an emp record into the database.
import java.sql.*;
import oracle.jdbc.*;
try {
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
String sql =
"INSERT INTO emp " +
"(emp_id,emp_f_name,emp_l_name,emp_salary,dept_id) " +
"VALUES(?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,emp_id);
pstmt.setString(2,emp_f_name);
pstmt.setString(3,emp_l_name);
pstmt.setFloat(4,emp_salary);
pstmt.setInt(5,dept_id);
pstmt.executeUpdate();
pstmt.close();
}
catch(SQLException e) {
System.err.println("ERROR! Adding Employee: "
+ e.getMessage());
}
}
}
There is nothing out of the ordinary here. Well, almost nothing. 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 and provides the fastest
access to the database.