Java-try-catch内的变量范围-大多数答案与Java官方教程之间的对比

问题描述 投票:0回答:1

我正在阅读以下official guide,但发现一个问题,将这两个代码片段一起使用将导致错误(stmt对象无作用域:]

处理ResultSet对象

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对象的实际作用域在尝试块。

我的问题很简单,这两个代码块可以一起工作吗?

我发现的答案是否定的,仅将stmt对象的实例移动到try块之外会导致一个有效的代码段。

有人能给我他的想法吗?我只想了解我是否仍不清楚该论点的某些方面。

非常感谢任何人都会尝试帮助我。

java scope try-catch-finally
1个回答
0
投票
大概,您已经在stmt内部而不是外部声明了try对象。代码应如下所示:

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省略了finally块这一事实(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) { JDBCTutorialUtilities.printSQLException(e); }

您可以在此处阅读有关AutoClosabletry with resources的更多信息:

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


0
投票
为了使之明确,您应该将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(); } }

© www.soinside.com 2019 - 2024. All rights reserved.