Using Oracle Database 10g Express Edition with Java

This article shows how to connect to Oracle Database 10g Express Edition using JDBC.

I use J2SE 5.0 (c:\jdk1.5.0) and Oracle Database 10g Express Edition on Windows XP (f:\oraclexe) for this article.

The following is the batch file used to set PATH and CLASSPATH.

path c:\jdk1.5.0\bin;f:\oraclexe\app\oracle\product\10.2.0\server\BIN
set classpath=.;f:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar

Connecting using OCI driver

The following program shows how to connect to Oracle using OCI driver.
import  java.sql.*;

public class OracleOCIConnection
{
 public static void main(String args[])
 {
  try
  {
   // load oracle driver
  Class.forName("oracle.jdbc.driver.OracleDriver");
  // connect using Native-API (OCI) driver
  Connection con = DriverManager.getConnection("jdbc:oracle:oci8:@","hr","hr" );
  System.out.println("Connected Successfully To Oracle using OCI driver");
  con.close();
  }
  catch(Exception ex)
  {
    ex.printStackTrace();
  }
 }
}

Connecting using Thin driver

The following program uses thin driver of Oracle to connect to Oracle. The default service name in Oracle Database 10g Express Edition is xe and port number for listener is 1521.
import  java.sql.*;

public class OracleThinConnection
{
 public static void main(String args[])
 {
  try
  {
   // load oracle driver
  Class.forName("oracle.jdbc.driver.OracleDriver");
  // connect using Thin driver
  Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr");
  System.out.println("Connected Successfully To Oracle");
  con.close();
  }
  catch(Exception ex)
  {
    ex.printStackTrace();
  }
 }
}

Connecting using Data Source - OracleDataSource

Connecting to Oracle using Driver Manager is deprecated in the new version. Instead it is recommended to use OrcleDataSource to get connection. The following program shows how to connect to Oracle using OracleDataSource.
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.*;

class DSConnection
{
 public static void main (String args[]) throws SQLException
 {
  OracleDataSource ods = new OracleDataSource();
  ods.setURL("jdbc:oracle:thin:hr/hr@localhost:1521/XE");
  Connection con = ods.getConnection();
  System.out.println("Connected");
  con.close();
 }
}

P.Srikanth