jdk1.7引入了资源自动关闭的接口AutoCloseable。一些资源也实现了该接口,如preparedStatement、Connection、InputStream、outputStream等等资源接口。在使用的时候只需要把资源在try块中用小括号括起来就可以了。
String sql = "select 1 from dual";
try
(
PreparedStatement pstmt = toConn.prepareStatement(sql);
PreparedStatement pstmt1 = fromConn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
ResultSet rs1 = pstmt1.executeQuery()
)
{
if(rs.next() || rs1.next()){
}
}
catch (SQLException e) {
log.error("test conn fail:", e);
e.printStackTrace();
throw new IllegalStateException("mysql链接发生异常!");
}
小括号里的资源最后一句不能加“;”。想要关闭的资源放里面,不需要在finally里再写rs.close,pstmt.close了。//此处有问题,我的需要加;
可以做个小实验,验证下AutoCloseable接口的作用
<p>public class TestAutoColseable {</p><p> public static void main(String[] args) {</p><p> try
(MyResource mr = new MyResource())
{
mr.doSomething();
} catch (Exception e) {
e.printStackTrace();
}finally{
}
}
}</p>
<p>public class MyResource implements AutoCloseable{</p><p> @Override
public void close() throws Exception {
System.out.println("资源被关闭了!");
}
public void doSomething(){
System.out.println("干活了!");
}
}
</p>
运行main方法就可以看到效果了。
---------------------
作者:执着的核桃
来源:CSDN
原文:https://blog.csdn.net/hetaolife/article/details/46889133
版权声明:本文为博主原创文章,转载请附上博文链接!