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 final clause. The steps in the preceding slides are summarized in the following example, which performs the following tasks:
  1. Import packages.
  2. Open an OracleDataSource.
  3. Connect to the database xe.
  4. Create a Statement object.
  5. Execute an SQL statement.
  6. Process the result set.
  7. Close the result set, statement, and connection.

SQL (p2.txt) =

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

  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.

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

// Import the following packages to use JDBC.
import  java.sql.*;
import  java.io.*;
import  oracle.sql.*;
import  oracle.jdbc.*;
import  oracle.jdbc.pool.OracleDataSource;

class  CloseConnection {
  public static void  main( String args[ ] ) throws SQLException {
    String user     = "C##user_id";
    String password = "password";
    String database = "20.185.147.112:1521/xe";

    // Open an OracleDataSource and get a connection.
    OracleDataSource ods = new OracleDataSource( );
    ods.setURL     ( "jdbc:oracle:thin:@" + database );
    ods.setUser    ( user );
    ods.setPassword( password );
    Connection conn = ods.getConnection( );

    try {
      // Read the parameter, sql.
      FileInputStream    stream     = new FileInputStream  ( "p2.txt" );
      InputStreamReader  iStrReader = new InputStreamReader( stream );
      BufferedReader     reader     = new BufferedReader   ( iStrReader );
      String  sql = reader.readLine( );
      if ( sql == null )  sql = "";
      else  sql = sql.trim( );
 
      try {
        // Query the employee names. 
        Statement  stmt = conn.createStatement( ); 
        System.out.println( "<font color='#3366CC'><h4>" + sql + "</h4></font>" );
        if ( stmt.execute( sql ) ) {
          ResultSet  rset = stmt.getResultSet( );
          // Print the names. 
          while ( rset.next( ) )
            System.out.println( rset.getString( 1 ) );  
          // Close the result set.
          rset.close( );
        }
        // Close the statement. 
        stmt.close( );
      }
      catch( SQLException e ) {
        System.out.println( e );
      } 
    }
    catch( IOException e ) { System.out.println( e ); }
    // Close the connection.
    conn.close( );
  }
}




      A stitch in time saves nine.