Try-with-resources is an Advanced Java feature (introduced in Java 7) that automatically closes JDBC resources such as Connection, Statement, and ResultSet. It helps prevent memory leaks and simplifies exception handling.
AutoCloseablefinally to close JDBC objectsIn JDBC, database objects like connections and statements are expensive. Try-with-resources ensures they are closed in the correct order even if an exception occurs.
// Syntax of try-with-resources
try(ResourceType resource = new ResourceType()) {
// use the resource safely
}
Click "Run Simulation" to see the order of execution
// JDBC example using try-with-resources
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TryWithResourcesDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String pass = "password";
try(
Connection con = DriverManager.getConnection(url, user, pass);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students")
) {
while(rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
The program prints all student records from the database. Once execution completes, the ResultSet, Statement, and Connection are closed automatically without explicit code.
PreparedStatement with try-with-resourcesfinally into try-with-resources