使用try-with-resources java关闭数据库连接

问题描述 投票:0回答:2

我的数据库具有原始的get方法。我需要通过其ID获取课程,然后关闭连接和声明。

public Course get(int id) throws ClassNotFoundException, SQLException {
        try (Connection connection = ConnectionConfig.getDbConnection();
             PreparedStatement statement = connection.prepareStatement(GET_COURSE)){
            statement.setInt(1, id);
            ResultSet course = statement.executeQuery();
            course.next();
            String result = course.getString(1);
            return new Course(id, result);
        }
    }

我想用try-with-resources来做。它会在这段代码中起作用吗,或者由于块中的return语句而无法自动关闭?另一方面,我不想在此块之外使用return,因为方法可以返回具有null字段的对象。在这种情况下,哪种方法形式最有效,最易读?预先谢谢你,我知道这是一个很业余的问题)

java database connection coding-style try-with-resources
2个回答
0
投票

关闭连接代码通常写在finally块中

Connection connection = null;
try {
connection = ConnectionConfig.getDbConnection();
//do all the stuff

}
finally{
connection.close()
}

0
投票

该连接将通过try with resources块关闭。这样做的条件是给定的类实现AutoCloseable。已经是这种情况。

可以看出here

© www.soinside.com 2019 - 2024. All rights reserved.