2014-10-02 35 views
3

我正在使用Java語句在PostgreSQL數據庫中執行存儲過程。像這樣:Java編寫的語句沒有結果集?

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這個流不關閉。

+1

請注意,有時(取決於數據庫和具體情況)o f存儲過程),您實際上需要**來讀取存儲過程的**整個結果集,以實際完成所有工作。 – 2014-10-02 18:00:52

回答

1

如果我理解你的問題,那麼你可以使用PreparedStatmenet.execute()來代替(這樣你就不會得到ResultSet)。

即,改變這個

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

preparedStatement.execute(); 
0

是的,你仍然希望結果集被關閉。

1

生成它的Statement對象關閉一個結果對象被自動關閉。所以你可以關閉語句來關閉ResultSet流。

更多細節

訪問http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html雖然如果你的要求是執行存儲過程,你可以使用JDBC 調用語句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();   
     }   
}