Java JDBC连接尝试使用资源

Java JDBC连接尝试使用资源,java,jdbc,try-with-resources,Java,Jdbc,Try With Resources,我是Java编程新手,对如何使用资源有疑问 共享代码 String语句=”“; 数据源ds=createDSConnection(); if(ds==null)返回; try(PreparedStatement prepare=ds.getConnection().PreparedStatement(语句)){ //语句值 prepare.execute(); }捕获(例外e){ } 这将同时关闭PrepareStatement和db.connection(),还是只关闭PreparedSta

我是Java编程新手,对如何使用资源有疑问 共享代码

String语句=”“;
数据源ds=createDSConnection();
if(ds==null)返回;
try(PreparedStatement prepare=ds.getConnection().PreparedStatement(语句)){
//语句值
prepare.execute();
}捕获(例外e){
}

这将同时关闭PrepareStatement和db.connection(),还是只关闭PreparedStatement?

所示代码将仅关闭PreparedStatement,并泄漏连接。如果要同时关闭这两个资源,则需要在资源块中为每个资源使用一条语句:

try (Connection connection = ds.getConnection();
     PreparedStatement prepare = connection.prepareStatement(statement)) {
    // your code here
}