You have a good question - I don’t understand the “official example” either. Finally, a block, of course, is enough.
However, your code has more serious errors, namely, if rs.close () throws an exception, you will have a stmt and conn leak, and you will also ignore this exception silently. This is what you should not do. Since Java 7, using the try-with-resources construct, is the preferred way, but if you cannot get there, at least handle each possible exception (rs, stmt, conn) separately so that they do not cause each other to leak.
For example, for this purpose, DbUtils has closeQuietly () just because it was a normal script. Personally, I would go somewhere like Spring's JDBCTemplate , which does similar things behind the scenes.
Edit: try-with-resources is explained by Oracle here . In short, you would do it something like this:
try (Connection conn = yourCodeToGetConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query)) { while (rs.next()) { String coffeeName = rs.getString("COF_NAME"); int supplierID = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt("SALES"); int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); } } catch (SQLException ex) {
If the try statement automatically handles conn , stmt and rs closures in all cases and order (in the reverse order in which you specify them). Possible exceptions that you still need to resolve.
source share