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:
Import packages.
Register an Oracle JDBC thin driver.
Connect to the database aero.
Create a Statement object.
Execute an SQL statement.
Processe the result set.
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( );
}
}