我编写了一个关闭3种关闭类型的方法:
java.sql.Connectionjava.sql.PreparedStatementjava.sql.ResultSet public static void closeAll(final Connection connection,
final PreparedStatement statement,
final ResultSet rs)
throws SQLException
{
try
{
if (rs != null)
{
rs.close();
}
}
finally
{
try
{
if (statement != null)
{
statement.close();
}
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}在Java 6中有简化它的方法吗?
在Java7中,我可以使用AutoCloseable接口:
public static void closeAll(final AutoCloseable ... closeables)
{
if (closeables != null && closeables.length > 0)
{
for (final AutoCloseable closeable: closeables)
{
try
{
closeable.close();
}
catch (final Exception ex)
{
// log it
}
}
}
}这是更好的解决办法吗?
发布于 2014-07-17 17:16:41
当创建ResultSet的Statement关闭时,它会自动关闭。当创建Statement的Connection关闭时,它会自动关闭。
如果要关闭所有内容,只需关闭Connection即可。
发布于 2015-02-13 10:34:35
查看更接近的番石榴(可怜的人尝试使用jdk6的资源):https://code.google.com/p/guava-libraries/wiki/ClosingResourcesExplained
像这样的东西应该能起作用(没有测试)
Closer closer = Closer.create();
try {
closer.register(connection);
closer.register(statement);
closer.register(rs);
// do stuff with in and out
} catch (Throwable e) { // must catch Throwable
throw closer.rethrow(e);
} finally {
closer.close();
}然而,这仍然是样板,我不会写这样的代码。例如,如果您使用Spring,请检查JdbcTemplate以避免它。
发布于 2015-02-13 08:04:39
我不知道您的问题是什么,但我认为对于Java 7来说,这就是您是如何做到的。
在这里,我正在查询一些“测试表”来获取一些数据。
对您来说,所有关闭连接的头痛都是由“尝试资源”语句完成的。你只需要坐下来,放松一下,看看你的日志中是否有错误信息;)
private void getDataFromTable(String date)
throws Exception
{
try (Connection db = ds.getConnection()) {
try (PreparedStatement ps = db.prepareStatement("select * from testtable")) {
ps.setString(1, date);
try (ResultSet rs = ps.executeQuery()) {
while(rs.next){
}
}
}
} catch (SQLException ex) {
throw new RunTimeException("Something went wrong here", ex);
}
}https://codereview.stackexchange.com/questions/57182
复制相似问题