Database A connection is owned and managed by a database, the class simply gives you access to this database resource. If you do not close the connection, then the Java class may be garbage collected, but the database may not be able to say that the connection is no longer in use, which can result in wasting database resources (as long as the timeout on side of the database) or even a leak.
So, when you finish using Connection , you should be sure to explicitly close it by calling its close() method. This will allow the garbage collector to remember the memory as early as possible and more importantly , it releases any other database resources (cursors, descriptors, etc.) that the connection can connect to.
The traditional way to do this in Java is to close your ResultSet , Statement and Connection (in that order) in the finally block when you are done with them, and the safe template looks like this:
Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { // Do stuff ... } catch (SQLException ex) { // Exception handling stuff ... } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { /* ignored */} } if (ps != null) { try { ps.close(); } catch (SQLException e) { /* ignored */} } if (conn != null) { try { conn.close(); } catch (SQLException e) { /* ignored */} } }
The finally block can be slightly improved (to avoid null checking):
} finally { try { rs.close(); } catch (Exception e) { } try { ps.close(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } }
But, nevertheless, this is very verbose, so you usually use the helper class to close objects in the methods of the helper method with zero use, and the finally block becomes something like this:
} finally { DbUtil.closeQuietly(rs); DbUtil.closeQuietly(ps); DbUtil.closeQuietly(conn); }
And, in fact, Apache Commons DbUtils has DbUtils that does exactly that, so there is no need to write your own.
In your case, this will solve the exception problem, but not debugging (and you will spend the database resources until the timeout appears on the database side). So, 1. do not debug your code using the production database. 2. Try to debug the session to the end.