Junior — Middle
How should you properly close a connection in a database or network protocol?
sobes.tech AI
Answer from AI
Properly closing a connection in a database or network protocol involves closing all open resources to prevent memory leaks and locks. In Java, working with a database typically uses try-with-resources or explicitly calls the close() method in a finally block.
Example with JDBC:
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
// process result
}
} catch (SQLException e) {
e.printStackTrace();
}
// Resources are automatically closed here
If try-with-resources is not used, then closing should be done in a finally block:
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
// work with connection
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
For network connections (e.g., sockets), it is also important to call the close() method after work is finished to free resources and properly close the connection.