【问题标题】:Java prepared statement without result set?没有结果集的Java准备语句?
【发布时间】:2014-11-27 16:54:45
【问题描述】:

我正在使用 Java 准备好的语句在 PostgreSQL 数据库中执行存储过程。像这样:

    String sql = "select testFkt(?,?,?,?,?)";
    try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
        preparedStatement.setInt(1, a
        preparedStatement.setInt(2, b);
        preparedStatement.setInt(3, c);
        preparedStatement.setByte(4, d);
        preparedStatement.setString(5, "test");
        try (ResultSet result = preparedStatement.executeQuery()) {

        }
    }

存储过程返回一个结果,但我对结果不感兴趣。

我仍然必须使用ResultSet(并尝试使用)还是可以只使用preparedStatement.executeQuery()

我担心会打开一个流或类似的东西,因为存储过程返回一个结果,如果我不使用ResultSet,这个流不会关闭。

【问题讨论】:

  • 请注意,有时(取决于数据库和存储过程的具体情况),您实际上需要读取存储过程的整个结果集实际完成所有工作。

标签: java postgresql jdbc prepared-statement resultset


【解决方案1】:

是的,您仍然希望关闭结果集。

【讨论】:

    【解决方案2】:

    如果我理解您的问题,那么您可以改用PreparedStatmenet.execute()(这样您就不会得到ResultSet)。

    也就是改这个

    try (ResultSet result = preparedStatement.executeQuery()) {
    }
    

    preparedStatement.execute();
    

    【讨论】:

      【解决方案3】:

      当生成它的 Statement 对象关闭时,ResultSet 对象会自动关闭。因此,您只需关闭语句即可关闭 ResultSet Stream。

      访问http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html了解更多详情

      虽然如果您的要求是执行存储过程,您可以使用 JDBC Callable Statement API

      访问http://docs.oracle.com/javase/7/docs/api/java/sql/CallableStatement.html了解更多详情

      示例如下:

      Connection dbConnection = null;         
      CallableStatement callableStatement = null;  
      String storedProc = "{call storedProc (?,?)}";
          try{
              dbConnection = getDBConnection();
              callableStatement = dbConnection.prepareCall(storedProc); 
              callableStatement.setInt(1, 1);  
              callableStatement.registerOutParameter(2, java.sql.Types.DATE); 
              callableStatement.executeUpdate();                                     
          } catch(SQLException e) {
              //handle exception
          } finally {             
             if (callableStatement != null) {         
                  callableStatement.close();          
             }            
             if (dbConnection != null) {  
                  dbConnection.close();           
             }        
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-16
        • 2021-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多