![](/img/trans.png)
[英]Should I use a try-with-resources statement for each line of log?
[英]Should I declare EVERY resource in try-with-resources Statement?
在我搜索过的许多 try-with-resource 示例中,Statement 和 ResultSet 是单独声明的。 正如 Java 文档中提到的,资源的 close 方法是按照它们创建的相反顺序调用的。
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql) ) {
} catch (Exception e) {
}
但是现在我的函数中有多个查询。
我可以在一行中创建 Statement 和 ResultSet 吗? 我的代码是这样的:
try (ResultSet rs = con.createStatement().executeQuery(sql);
ResultSet rs2 = con.createStatement().executeQuery(sql2);
ResultSet rs3 = con.createStatement().executeQuery(sql3)) {
} catch (Exception e) {
}
如果我只在一行中声明它们,它是否仍然关闭 ResultSet 和 Statement 的资源?
当您仔细查看时,您会发现该概念称为 try-with-resource s 。
注意复数! 整个想法是您可以在单个语句中声明一个或多个资源,并且 jvm 保证正确处理。
换句话说:当资源在语义上属于一起时,最好将它们声明在一起。
是的,它的工作原理与您在问题中所说的完全一样,多个语句以分号分隔。
您可以在 try-with-resources 语句中声明一个或多个资源。 以下示例检索打包在 zip 文件 zipFileName 中的文件的名称,并创建一个包含这些文件名称的文本文件:
try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
ResultSet
实现了AutoCloseable
,这意味着 try-with-resources 也将在使用AutoCloseable
强制关闭它。
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.