Java 7 优雅的自动资源管理,java资源管理,Java7以前的做法Co
分享于 点击 24781 次 点评:51
Java 7 优雅的自动资源管理,java资源管理,Java7以前的做法Co
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.}}
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 statements for handles the exceptions}
用户点评