jdk7 autocloseable接口的使用

jdk1.7引入了资源自动关闭的接口AutoCloseable。一些资源也实现了该接口,如preparedStatement、Connection、InputStream、outputStream等等资源接口。在使用的时候只需要把资源在try块中用小括号括起来就可以了。

1
2
3
4
5
6
7
8
9
String sql = "select 1 from dual";
try (PreparedStatement pstmt = toConn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();) {
if (rs.next()) {
}
} catch (SQLException e) {
log.error("查询出错", e);
e.printStackTrace();
}