Sunday, June 5, 2011

Now all we have to do is close the connection

Now all we have to do is close the connection. Actually we should close all of the instances of Connection, Statement and ResultSet and
it's done in reverse order from which they were created:


if (rs != null)
rs.close();
if (statement != null)
statement.close();
if (con != null)
con.close();


For many of the code statements above it is required to handle an SQLException in case anything goes wrong.
Thus you'll have to enclose much of the code in a try / catch block which were excluded in the example to make it more readable.


// Declare the variables outside the try block to be able to call them
// in a finally block where the closing should take place.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;


try {

//all code here

} catch (SQLException ex) {

ex.printStackTrace();

} finally {

//the code for closing here
}

No comments:

Post a Comment

 
THANK YOU FOR VISITING