Java 7 优雅的自动资源管理

2014-11-24 07:23:49 · 作者: · 浏览: 2

[代码] Java7以前的做法


Connection connection = null;
Statement statement = null;


try{
connection = DriverManager.getConnection(“databaseurl”,”username(opt)”,”password(opt)”);
statement = connection.createStatemnet();
boolean executionStatus= statement.execute(“query”);
}catch(Exception e){
//Block of code for handle the exception
e.printStacktrace();
}finally{
try{
statement.close();
connection.close();
}catch(Exception e){
//block of statements for handle exceptions.
}
}


[代码] Java 7的做法(无需手工释放资源)


Connection connection = null;
Statement statement = null;


try(//请注意这里的小括号,不是大括号
connection =    DriverManager.getConnection(“databaseurl”,”username(opt)”,”password(opt)”);
statement = connection.createStatemnet()
)
{
boolean executionStatus= statement.execute(“query”);
}catch(Exception e){
//block of statements for handles the exceptions
}