Sobes.tech
Junior

How to properly close a database connection?

sobes.tech AI

Answer from AI

Using the try-with-resources block.

// Declaration of resources that will be automatically closed
try (  
    Connection connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", ""); // Getting the Connection object
    Statement statement = connection.createStatement();  // Creating the Statement object
    ResultSet resultSet = statement.executeQuery("SELECT 1") // Executing the query and obtaining ResultSet
) {  
    // Working with data from ResultSet or performing other database operations
    while (resultSet.next()) {  
        System.out.println(resultSet.getInt(1));  
    }  
} catch (SQLException e) {  
    // Handling possible SQLException
    e.printStackTrace();  
}  

Advantages of this approach:

  • Automatic closing: Resources (Connection, Statement, ResultSet) are guaranteed to be closed after exiting the try block, even if exceptions occur.
  • Clean code: Does not require explicit close() calls in a finally block, reducing boilerplate code.
  • Exception handling: If an exception occurs during resource closing, it will not suppress an exception that occurred inside the try block.

An alternative, less preferred method with explicit closing in a finally block:

Connection connection = null;  
Statement statement = null;  
ResultSet resultSet = null;  

try {  
    connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");  
    statement = connection.createStatement();  
    resultSet = statement.executeQuery("SELECT 1");  
    // Working with data
    while (resultSet.next()) {  
        System.out.println(resultSet.getInt(1));  
    }  
} catch (SQLException e) {  
    e.printStackTrace();  
} finally {  
    // Explicitly closing resources in reverse order of their acquisition
    if (resultSet != null) {  
        try {  
            resultSet.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
    if (statement != null) {  
        try {  
            statement.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
    if (connection != null) {  
        try {  
            connection.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
}  

This method is more verbose and error-prone, especially when handling exceptions during resource closing. Using try-with-resources is preferred.

How to properly close a database connection? — Java - sobes.tech