Slide 12.1: JDBC (Java DataBase Connectivity)
Slide 12.3: A typical JDBC API usage sequence
Home

A Sample JDBC Program


The following sample program shows how to retrieve and list employee information from the EMPLOYEE_TBL table, which is partially defined as
   CREATE TABLE  employee_tbl (
     employee_id    NUMBER(6)     PRIMARY KEY, 
     first_name     VARCHAR2(20),
     last_name      VARCHAR2(25)  NOT NULL,
     email          VARCHAR2(25)  NOT NULL,
     phone_number   VARCHAR2(20) ) ;
This definition can be found at
  /home/Agassiz/project/oracle/OraHome1/demo/schema/human_resources
If the second input field is empty, the program will list the information of all employees.

                           
/*********************************************************
 
  This program shows how to list the employee information
    in the employee_tbl table.
 
  To use this program, you need to create a table
    employee_tbl by using the following command:
 
  SQL> CREATE TABLE  employee_tbl (
    2    employee_id   NUMBER(6)     PRIMARY KEY, 
    3    first_name    VARCHAR2(20),
    4    last_name     VARCHAR2(25)  NOT NULL,
    5    email         VARCHAR2(25)  NOT NULL,
    6    phone_number  VARCHAR2(20) ) ;
 
  Table created.
 
*********************************************************/
// You need to import the java.sql package to use JDBC.
import  java.sql.*;
import  java.io.*;
 
class  Select {
  public static void  main( String args[ ] ) 
    throws SQLException {
    // Load the Oracle JDBC driver.
    DriverManager.registerDriver ( new oracle.jdbc.driver.OracleDriver( ));
    // Connect to the database.  You can put a database 
    // name after the @ sign in the connection URL.
    Connection conn = DriverManager.getConnection (
      "jdbc:oracle:thin:@172.20.4.9:1521:aero", "userid", "password" );
    try {
      // Create a statement and query.
      Statement stmt = conn.createStatement( );
      String  query  = "SELECT  FROM employee_tbl WHERE";
              query += " last_name LIKE '%%'";
      System.out.print( "<em>" + query + "</em><br /><br />" );
 
      // Execute the query.
      ResultSet rset = stmt.executeQuery( query );
 
      // Iterate through the results and print them.
      while ( rset.next( ) )
        System.out.println ( rset.getString( 1 ) + "<br />" );
      // Close the RseultSet.
      rset.close( );
 
      // Close the Statement.
      stmt.close( );
    }
    catch ( Exception e ) {
      System.out.println( e );
    } 
    // Close the Connection.
    conn.close( );
  }
}