朋友说,在他们团队接受项目时,验证者向他们指出,该对象是明确关闭的Statement。我也问了自己这个问题,然后去看看官方文档是怎么说的:
通常最好在使用完资源后立即释放资源,以避免占用数据库资源。
因此,显式关闭是一种很好的做法Statement,显然,这是通过以下方式完成的:
try {
// работа со statemen'ом
} catch (SQLException e) {
LOGGER.error("Failed to execute SQL statement: {}.", SQL_PROCEDURE_CREATE_ACCOUNT);
throw new DaoException("Failed to execute SQL statement: " + SQL_PROCEDURE_CREATE_ACCOUNT, e);
} finally {
try {
statement.close();
} catch (SQLException e) {
//todo а если не удалось закрыть statement, что тогда делать?
LOGGER.error("Database access error occurs when trying to close Statement object.", e);
throw new DaoException("Database access error occurs when trying to close Statement object." + e);
}
}
问题:
statment如果尝试使用显式方法调用关闭对象时statement.close()抛出异常,如何处理对象SQLException,根据官方文档,可以在以下情况下抛出异常:
抛出:SQLException - 如果发生数据库访问错误
- 如果对象本身实现了接口,是否还需要显式关闭
statement方法调用?statement.close()StatementAutoCloseable
指定者:接口AutoCloseable中的close
Closeable/AutoCloseable这是使用数据库的典型代码
回答了你自己的问题
没错,这里必须补充一点,如果执行了隐式闭包,即 如果使用资源尝试,那么执行过程中发生的异常
close()应该单独捕获。该接口
AutoClosable不会自动关闭语句,而是隐式关闭它,就像上面提到的情况一样。现在
好吧,这里的原因可能不同,但在大多数情况下,这没什么意义,所以可以简单地忽略异常。