Friday, February 26, 2010

JDBC Connecting to Oracle

Thin & OCI Drivers
Oracle provides two main types of drivers.
The OCI driver.
The OCI (type 2) driver consists of java wrappers to the low-level Oracle Call Interface (OCI) libraries used by utilities like SQL*Plus to access the database server. The OCI driver offers potentially better performance that the thin driver. It however requires the OCI libraries to be installed on the local machine.

The ``thin'' driver.
Also referred to as type 4 driver, the thin driver is a pure Java implementation of Oracle's networking protocol (Net8). Being self-contained, it may be used on any machine with--or without Oracle installed--or even distributed with application classes in an applet.

Connecting to Oracle

We will review below how to access Oracle using both types of driver. First, we use the thin driver to connect to Oracle and execute an update statement. Note that the example below is only intended as an illustration. Try to understand the code. You will have opportunities for ``hands-on'' practice in the next section.

import java.io.*;
import java.sql.*;

public class OraThin {
public static void main(String[] args) {
try {
Connection con=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection(
"jdbc:oracle:thin:@machine_name:1521:database_name",
"scott",
"tiger");
Statement s=con.createStatement();
s.execute("
INSERT INTO BOOKS VALUES
(
'A Tale of Two Cities',
'William Shakespeare',
4567891231,
'5-JAN-1962'
)
");
s.close();
con.close();
} catch(Exception e){e.printStackTrace();}
}
}

* The package java.sql containing the JDBC classes is imported.
* The class OracleDriver, in the package oracle.jdbc.driver is dynamically loaded into the Java runtime using Class.forName(...).
* A connection is requested to the database corresponding to the connection URL with the statement DriverManager.getConnection(...).
* scott/tiger is an Oracle user/password.
* We use instances of the Connection and Statement classes to perform a database operation.
* The resources hold by these are released using their close() method.

If we want use the OCI driver, the JDBC connection URL above needs to be altered. The only element now required is the service name of the database: database_name. The remainder is resolved using the local Oracle configuration file.

DriverManager.getConnection(
"jdbc:oracle:oci8:@database_name", "scott","tiger");

No comments:

Post a Comment