Slide 14.33: Committing changes
  Slide 15.1: Mobile commerce
  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 illustrated in the following example, which registers an Oracle JDBC Thin driver, connects to the database, creates a Statement object, executes a query, and processes the result set.

import java.sql.*; 
import java.math.*;
import java.io.*;
import java.awt.*;

class JdbcTest { 
  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" );
    
    // Query the employee names 
    Statement stmt = conn.createStatement( ); 
    ResultSet rset = stmt.executeQuery( "SELECT ename FROM emp" );
    // Print the name out 
    while ( rset.next( ) )
      System.out.println( rset.getString( 1 ) );
    
    //close the result set, statement, and the connection
    rset.close( );
    stmt.close( );
    conn.close( );
  }
}