Slide 12.11: Committing changes
Slide 13.1: Indexing
Home

Closing the Connection


You must close your connection to the database once you finish your work. Use the close( ) method of the Connection object to do this:
   conn.close( );
Typically, you should put close( ) statements in a finally clause.

The steps in the preceding slides are summarized in the following example, which performs the following tasks:
  1. Import packages.
  2. Register an Oracle JDBC thin driver.
  3. Connect to the database aero.
  4. Create a Statement object.
  5. Execute an SQL statement.
  6. Processe the result set.
  7. Close the result set, statement, and connection.

                       
/*********************************************************

  This program shows how to close connections.

  To use this program, you need to create a table
    emp_tbl by using the following command:

  SQL> create table  emp_tbl (
    2    empno   integer  primary key,
    3    ename   varchar(64)  not null );

  Table created.

*********************************************************/

// You need to import the java.sql package to use JDBC.
import  java.sql.*;
import  java.io.*;

class  CloseConnection {
  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 {
      // Query the employee names. 
      Statement  stmt = conn.createStatement( ); 
      if ( stmt.execute( "" ) ) {
        ResultSet  rset = stmt.getResultSet( );
        // Print the results. 
        while ( rset.next( ) )
          System.out.println( rset.getString( 1 ) + "<br />");
        // Close the result set.
        rset.close( );
      }
      // Close the statement. 
      stmt.close( );
    }
    catch( SQLException e ) {
      System.out.println( e );
    }
    conn.close( );
  }
}