How to properly clean up JDBC resources in Java?

后端 未结 9 1949
说谎
说谎 2020-12-16 03:17

What is considered best practices when cleaning up JDBC resources and why? I kept the example short, thus just the cleaning up of the ResultSet.

finally
{
          


        
9条回答
  •  一向
    一向 (楼主)
    2020-12-16 03:35

    Nowadays JDK 7 gives you the easiest option to clean up resources:

    String query = "select COF_NAME, PRICE from COFFEES";
    try (Statement stmt = con.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            float price = rs.getFloat("PRICE");
            System.out.println(coffeeName + ", "  + price);
        }
    }
    

    The try statement ensures that each resource is closed at the end of the statement. See http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

提交回复
热议问题