How to Use JDBC with Oracle

Introduction

Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases.

This page describes how to use JDBC to connect to the UB Academic Oracle Service (AOS).

Setup

  1. Login to any 64-bit student Linux system.
  2. Set C Oracle environment variables contained in coraenv.sh:

    % source /util/oracle/coraenv.sh
    

Example One: DBTest.java

This example uses connection pooling.

A full working version of this code is attached as DBTest.java, below. Highlights:

  1. Write a foo.java file that includes code to establish an Oracle connection:
    • Import Oracle drivers:

        import oracle.jdbc.pool.OracleDataSource;
        

    • Establish a connection to the Oracle instance:

        OracleDataSource ods = new OracleDataSource();
        ods.setUser(user);
        ods.setPassword(pass);
        ods.setURL ("jdbc:oracle:thin:@aos.acsu.buffalo.edu:1521/aos.buffalo.edu");
        Connection conn = ods.getConnection();
        

Example Two: JDBCTest02.java

This example does not use connection pooling.

A full working version of this code is attached as JDBCTest02.java, below. Highlights:

  1. Oracle's JDBC driver is located in a Java package called oracle. In order to load the JDBC driver in your Java programs, include the line:

    Class.forName ("oracle.jdbc.driver.OracleDriver");
    

  2. However, if there is a problem, the above statement will throw an exception, so it's good programming practice to catch this exception within a try block:

    try {
       Class.forName ("oracle.jdbc.driver.OracleDriver");
    }
    catch (ClassNotFoundException e){
       System.out.println("Could not load the JDBC driver. Check your CLASSPATH.");
       System.exit(0);
    }
    

  3. Use this connection string syntax to connect to AOS:

    Connection con = DriverManager.getConnection("jdbc:oracle:thin:"+user+"/"+passwd+"@aos.acsu.buffalo.edu:1521/aos.buffalo.edu");

Test

  1. Compile foo.java:

    % javac foo.java
    

  2. Run compiled Java code:

    % java foo
    

References

  1. http://en.wikipedia.org/wiki/JDBC
  2. http://java.sun.com/javase/technologies/database/
  3. http://www.oracle.com/technology/tech/java/sqlj_jdbc/index.html
  4. http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html
  5. http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdb...
AttachmentSize
DBTest.java743 bytes
JDBCTest02.java2.64 KB