gpt4 book ai didi

java - 如果所有调用者都确保关闭它,我是否需要在准备好的语句创建上使用 try-with-resource?

转载 作者:行者123 更新时间:2023-11-30 06:45:37 25 4
gpt4 key购买 nike

我正在处理一些遗留代码,它看起来像这样:

    PreparedStatement prepared_statement;
if (x > 0) {
prepared_statement = connect.prepareStatement(sql_query);
prepared_statement.setInt(1, id);

for (int i = 0; i < list_size; i++) {
String internal_token_symbol = callMethod(coin, exchange_list.get(i));
}
} else {
prepared_statement = connect.prepareStatement(sql_query);
prepared_statement.setInt(1, token_id);
}

return prepared_statement;

这里的关键是它创建了一个准备好的语句,然后返回它以备后用。请注意,如果发生异常,它不会使用 try-with-resource 或关闭。

我的问题是,如果此方法的每个 调用方都使用 try-with-resource,是否存在无法关闭语句的危险?例如如果所有调用者都这样做:

try (PreparedStatement ps = resultOfCallingMyMethod()) {
// Use the prepared statement
}

我自己通过这样做证明了这一点:

@Test
public void testIPrint() throws IOException { // this prints
try (MyCloseable closeable = new MyCloseable()) {

}
}

@Test
public void testIAlsoPrint() throws IOException, InterruptedException { //this doesn't print :(
try (MyCloseable closeable = iThrowAnException()) {

}
}

private MyCloseable iThrowAnException() {
MyCloseable closeable = new MyCloseable();
if (true) {
throw new RuntimeException();
}
return closeable;
}

public static class MyCloseable implements Closeable {
@Override
public void close() throws IOException {
System.out.println("I was closed!");
}
}

最佳答案

不,没关系,唯一的问题是:如何确保每个调用者都在使用try-with-resource?

通常,我会尽量不将 PreparedStatement 泄漏到类之外。这样,关闭它仍然是类(class)的责任。

编辑:实际上,按照 Mike Strobel 的评论:如果 x > 0callMethod 抛出异常,它不会被返回给来电者,不会关闭。

关于java - 如果所有调用者都确保关闭它,我是否需要在准备好的语句创建上使用 try-with-resource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48675176/

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