The following example shows how it is necessary to put the closing code in a finally block with exception handling, which decreases the readability of the code:
@Resource(lookup = "java:/MySQLDS")
private DataSource ds;
. . . .
String sql = "select * from customer";
List list = new ArrayList();
Connection con =null;
PreparedStatement ps =null;
ResultSet rs =null;
try {
con = ds.getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
list.add(rs.getInt("id"));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { }
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) { }
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) { }
}
}
And here's the same example rewritten to use try-with-resource:
@Resource(lookup = "java:/MySQLDS")
private DataSource ds;
. . . .
String sql = "select * from customer";
List list = new ArrayList();
try (Connection con = ds.getConnection();
PreparedStatement ps = con.prepareStatement(sql);) {
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
list.add(rs.getInt("id"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Nessun commento:
Posta un commento