Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ปิดทรัพยากรอัตโนมัติใน Java ด้วย try-with-resources

สามารถปิดทรัพยากร (Resources) อัตโนมัติได้ด้วย try-with-resources ใน JDBC (รองรับตั้งแต่ Java 7)

ไวยากรณ์


try (Declaration of resource) {
    // body...
} catch (SQLException e) {
    e.printStackTrace();
}

เป็น try statement ที่ประกาศ resource หนึ่งหรือหลายตัวในวงเล็บ Resource คือออบเจ็กต์ที่ควรปิดเมื่อไม่ใช้แล้ว

  • ประกาศ resource หลายตัวได้ ทั้งหมดจะปิดอัตโนมัติท้ายบล็อก
  • Resource ต้อง implement java.lang.AutoCloseable หรือ java.io.Closeable
  • ใน JDBC ใช้ได้กับ: Connection, Statement, PreparedStatement, CallableStatement, ResultSet, RowSet

ตัวอย่างโค้ด


import java.sql.*;

public class TryWithResources_Example {
    public static void main(String args[]) {
        String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
        System.out.println("Connection established......");
        
        try (Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
             Statement stmt = con.createStatement()) {
            
            try (ResultSet rs = stmt.executeQuery("select * from MyPlayers")) {
                while (rs.next()) {
                    System.out.print(rs.getInt("ID") + ", ");
                    System.out.print(rs.getString("First_Name") + ", ");
                    System.out.print(rs.getString("Last_Name") + ", ");
                    System.out.print(rs.getDate("Date_Of_Birth") + ", ");
                    System.out.print(rs.getString("Place_Of_Birth") + ", ");
                    System.out.print(rs.getString("Country"));
                    System.out.println();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

คำอธิบาย

  • Connection และ Statement ประกาศใน try แรก จะปิดอัตโนมัติ
  • ResultSet ประกาศใน try ทอด (nested) จะปิดอัตโนมัติก่อน
  • ไม่ต้องเขียน finally block เพื่อ close() เอง
  • ลดความเสี่ยง Resource Leak ได้มาก

ผลลัพธ์


Connection established......
1, Shikhar, Dhawan, 1981-12-05, Delhi, India
2, Jonathan, Trott, 1981-04-22, CapeTown, SouthAfrica
...