当在常规Java块中使用PreparedStatements时,我可以在需要时更改PreparedStatement以运行不同的查询,如下所示:
String sqlStatement = "update someTable set someValue = true";
try{
    PreparedStatement pstmt = con.prepareStatement(sqlStatement);
    pstmt.executeUpdate();
    /* Here I change the query */
    String anotherSqlStatement = "update aDifferentTable set something = false";
    pstmt = con.prepareStatement(anotherSqlStatement);
    pstmt.executeUpdate();
}
catch(Exception ex){
    ...
}使用Java的试用-的正确方法是什么?这就是我已经尝试过的,但是“不能分配”语句的资源pstmt“。
try(Connection con = DriverManager.getConnection(someConnection, user, password);
    PreparedStatement pstmt = con.prepareStatement(sqlStatement)){
    ResultSet rs = pstmt.executeQuery();
    ....
    /* Here I attempt to change the query, but it breaks */
    String anotherSqlStatement = "select something from someTable";
    pstmt = con.prepareStatement(anotherSqlStatement);
}
catch(Exception ex){
    ...
}我不想再次声明这个变量,我知道这会挫败使用-的目的,我只想把它分配给其他的东西。正确的方法是什么?
发布于 2016-05-13 18:29:45
考虑一下如果Java允许您这样做会发生什么。如果重新分配pstmt引用的内容,那么在执行第一个PreparedStatement之后,pstmt将引用第二个PreparedStatement。只对pstmt在块完成执行时引用的内容调用close方法,因此在第一个PreparedStatement上永远不会调用close。
相反,将嵌套的使用资源的尝试块设置为:
try (Connection con = DriverManager.getConnection(someConnection, user, password)) {
    try (PreparedStatement pstmt = con.prepareStatement(sqlStatement)) {
        pstmt.executeUpdate();
    }
    try (PreparedStatement pstmt = con.prepareStatement(anotherSqlStatement)) {
        pstmt.executeUpdate();            
    }
}这样,在不同的作用域中有两个pstmt局部变量。第一个PreparedStatement在第二个开始之前关闭。
https://stackoverflow.com/questions/37215886
复制相似问题