gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:14:42 25 4
gpt4 key购买 nike

我的数据库有原始的 get 方法。我需要通过它的 id 获取类(class),然后关闭连接和语句。

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 来做到这一点。它在此代码中工作吗?或者由于 block 中的 return 语句而自动关闭将不起作用?另一方面,我不想在这个 block 之外使用 return,因为方法可以返回带有 null 字段的对象。在这种情况下,哪种方法形式最有效且最具可读性?预先感谢您,我知道这是一个相当业余的问题)

最佳答案

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

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

}
finally{
connection.close()
}

关于java - 使用 try-with-resources java 关闭数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62437367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com