首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用PreparedStatement两次并尝试- with?

如何使用PreparedStatement两次并尝试- with?
EN

Stack Overflow用户
提问于 2016-05-13 17:20:28
回答 1查看 3.4K关注 0票数 3

当在常规Java块中使用PreparedStatements时,我可以在需要时更改PreparedStatement以运行不同的查询,如下所示:

代码语言:javascript
运行
复制
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“。

代码语言:javascript
运行
复制
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){
    ...
}

我不想再次声明这个变量,我知道这会挫败使用-的目的,我只想把它分配给其他的东西。正确的方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-13 18:29:45

考虑一下如果Java允许您这样做会发生什么。如果重新分配pstmt引用的内容,那么在执行第一个PreparedStatement之后,pstmt将引用第二个PreparedStatement。只对pstmt在块完成执行时引用的内容调用close方法,因此在第一个PreparedStatement上永远不会调用close。

相反,将嵌套的使用资源的尝试块设置为:

代码语言:javascript
运行
复制
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在第二个开始之前关闭。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37215886

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档