Keeping the database connection alive requires a significant number of resources – such as memory and CPU – so, it is a good idea to close the connection and release the allocated resources as soon as you no longer need them. In the case of pooling, the Connection object, when closed, is returned to the pool and consumes fewer resources.
Before Java 7, a connection was closed by invoking the close() method in a finally block:
try {
Connection conn = getConnection();
//use object conn here
} finally {
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The code inside the finally block is always executed, whether the exception inside the try block is thrown or not. However, since Java 7, the try-with-resources construct also does the job on any...