← Back to Chapters

Try-with-Resources (JDBC)

? Try-with-Resources (JDBC)

? Quick Overview

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.

? Key Concepts

  • Resources must implement AutoCloseable
  • Resources are closed automatically at the end of the try block
  • No need for finally to close JDBC objects
  • Cleaner, safer, and more readable code

? Syntax / Theory

In 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.

? View Code Example
// Syntax of try-with-resources
try(ResourceType resource = new ResourceType()) {
// use the resource safely
}

? Interactive Lifecycle Simulation

Click "Run Simulation" to see the order of execution

?
Connection
?
Statement
?
Result Set
Waiting to start...

? Code Example(s)

? View Code Example
// 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();
}
}
}

? Live Output / Explanation

Output

The program prints all student records from the database. Once execution completes, the ResultSet, Statement, and Connection are closed automatically without explicit code.

? Tips & Best Practices

  • Always prefer try-with-resources over manual closing
  • Declare multiple resources in a single try statement
  • Keep database credentials external (properties file)
  • Use meaningful exception handling

? Try It Yourself

  • Create a JDBC program using PreparedStatement with try-with-resources
  • Test behavior when an SQL exception occurs
  • Convert an old JDBC program using finally into try-with-resources