Java ready statement without result set?

I am using a Java prepared statement to execute a stored procedure in a PostgreSQL database. Like this:

    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()) {

        }
    }

      

Stored procedures return a result, but I am not interested in the result.

Should I use ResultSet

(and try), or can I just use preparedStatement.executeQuery()

?

My fear is that there is a stream or something like that open, because stored procedures return a result and that this stream is not closed if I don't use ResultSet

.

+3


source to share


3 answers


If I understand your question, you can use PreparedStatmenet.execute()

(this way you won't get ResultSet

).

That is, change this

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

      



to

preparedStatement.execute();

      

+1


source


The ResultSet object is automatically closed when the Statement that generated it is closed. So you can just close the statement to close the ResultSet stream.

Visit http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html for more details

Although if your requirement is to execute a stored procedure you can use the JDBC API



More on http://docs.oracle.com/javase/7/docs/api/java/sql/CallableStatement.html

See example below:

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();           
       }        
}

      

+1


source


yes, you still want the result set to be closed.

0


source







All Articles