使用资源尝试 Java 关闭数据库连接



我的数据库有原始的获取方法。我需要通过其 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);
}
}

我想用资源来做。它会在此代码中工作还是由于块中的 return 语句而自动关闭不起作用?另一方面,我不想在此块之外使用 return,因为方法可以返回带有 null 字段的对象。在这种情况下,哪种方法形式最有效和可读性最强?提前谢谢你,我知道这是一个相当业余的问题(

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

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

连接将由 try with resources 块关闭。这样做的条件是给定类实现自动关闭。情况已经如此。

正如在这里看到的

最新更新