【问题标题】:java try with resources : empty result setjava尝试资源:空结果集
【发布时间】:2018-05-21 13:23:02
【问题描述】:

我正在尝试使用 java try-with-resources 语句更新我的数据库中的用户。但是,我收到一条错误消息,提示我的结果集为空。在阅读了其他各种帖子后,他们建议使用 ps.executeUpdate() 而不是 ps.executeQuery(),但这会返回一个 int,它(说明非常明显)没有“自动关闭”类型,这意味着代码确实甚至没有通过编译。

有没有人有一个如何绕过这个的例子?

public void updateUser (String id, String value){

    try (Connection con = DriverManager.getConnection("jdbc:databasetype://localhost:5432/database");
         PreparedStatement ps = createUpdateStatement(con, id, value);
         ResultSet rs = ps.executeQuery())
    {
        System.out.println("Add operation completed");
    } catch(Exception e) {
        System.out.println("Exception: " + e.getMessage() + " Thrown by: " + e.getClass().getSimpleName());
    }
}

【问题讨论】:

    标签: java sql prepared-statement try-with-resources


    【解决方案1】:

    如果它们实现了Closeable,你只需要在 try 中的资源。正如您所说,原始整数不能将其移出 try-with-resources 并进入正文:

    public void updateUser (String id, String value)
    {
        try (Connection con = DriverManager.getConnection("jdbc:databasetype://localhost:5432/database");
             PreparedStatement ps = createUpdateStatement(con, id, value))
        {
            int result = ps.executeUpdate();
            System.out.println("Add operation completed");
        } catch(Exception e) {
            System.out.println("Exception: " + e.getMessage() + " Thrown by: " + e.getClass().getSimpleName());
        }
    }
    

    【讨论】:

      【解决方案2】:

      ps.executeUpdate 移动到try 的正文中:

      try (Connection con = DriverManager.getConnection("jdbc:databasetype://localhost:5432/database");
           PreparedStatement ps = createUpdateStatement(con, id, value)) {
          ps.executeUpdate();        
          System.out.println("Add operation completed");
      } catch(Exception e) {
          System.out.println("Exception: " + e.getMessage() + " Thrown by: " + e.getClass().getSimpleName());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-03
        • 1970-01-01
        • 2014-11-05
        • 2016-05-24
        • 2011-01-27
        • 2017-11-30
        • 1970-01-01
        相关资源
        最近更新 更多