Java 7 优雅的自动资源管理

[代码] 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
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwsdjy.html