Slide 14.22: JDBC (Java DataBase Connectivity)
  Slide 14.24: A typical JDBC API usage sequence
  Home


A Sample JDBC Program


The following sample program shows how to retrieve and list all the names (FIRST_NAME, LAST_NAME) from the EMPLOYEES table, which is partially defined as
   CREATE TABLE employees (
     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

// Import the java.sql package to use JDBC.
import java.sql.*;

class SelectExample {
  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.2.253:1521:aero",
      "userid", "password" );

    // Create a Statement.
    Statement stmt = conn.createStatement( );

    // Select first_name and last_name from the employees table.
    ResultSet rset = stmt.executeQuery(
      "select FIRST_NAME, " + "LAST_NAME from EMPLOYEES" );

    // Iterate through the result and print the employee names.
    while ( rset.next( ) )
      System.out.println(
        rset.getString( 1 ) + " " + rset.getString( 2 ) );

    // Close the RseultSet
    rset.close( );

    // Close the Statement
    stmt.close( );

    // Close the connection
    conn.close( );
  }
}