我正在阅读以下官方指南,我发现了一个问题,将这两个代码片段一起使用会导致错误(没有 stmt 对象的范围(:
处理结果集对象
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "t" + supplierID +
"t" + price + "t" + sales +
"t" + total);
}
}
关闭连接
} finally {
if (stmt != null) { stmt.close(); }
}
如果我尝试在 finally 块中stmt.close()
,我会得到一个错误,因为他的作用域中没有 stmt 变量,这是因为(据我所知(stmt 对象的实际作用域在 try 块中。
我的问题很简单,这两个代码块可以一起工作吗?
我找到的答案是否定的,只有将 stmt 对象的实例化移动到 try 块之外才会导致工作片段。
有人可以告诉我他的想法吗?
我只是想了解这个论点的某些方面是否对我来说还不清楚。
非常感谢任何人会尽力帮助我。
据推测,您已经在try
内部声明了stmt
对象,而不是在外部声明了对象。代码应如下所示:
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "t" + supplierID +
"t" + price + "t" + sales +
"t" + total);
}
} finally {
if (stmt != null) { stmt.close(); }
}
但是,您可以使用Statement
实现AutoClosable
的事实,并使用try with resources
(Java 6 iirc中添加的Java功能(实际省略最终块。那看起来像:
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "t" + supplierID +
"t" + price + "t" + sales +
"t" + total);
}
} catch (SQLException e) {
// Log it
}
您可以在此处阅读有关AutoClosable
和try with resources
的更多信息:
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
要明确这一点,您应该将 stmt 分配给 null,以便它存在并初始化:
Statement stmt = null;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "t" + supplierID +
"t" + price + "t" + sales +
"t" + total);
}
} finally {
if (stmt != null) { stmt.close(); }
}