Search code examples
javaspringjdbctry-catchprepared-statement

How to close PreparedStatement


I have the following code on which I want to close the preparedStatement object as it is raised as a bug from sonar.

  public myfunction() throws SQLException {
            
           PreparedStatementCreator preparedStatementCreator = new PreparedStatementCreator() {
                String query = "";//let us assume a query
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement preparedStatement= connection.prepareStatement(query);
                    preparedStatement.setString();
                    preparedStatement.setString();
                }
            };
    int rows;
    try
    {
    rowNumbers = jdbcTemplate.update(preparedStatementCreator);
    }
    catch(....)
    {
    }
    catch(....)
    {
    }
    catch(....)
    {
    }
    }

How can I close the preparedStatement object? Most of examples I saw they mostly use try/finally or try with resources and then create object and use it try and close in finally. However, here the object is getting created in separate function and it is returned from there and then it is used. So creation and usage are happening at two different places. So I want to know both ways of handling this

  1. Before Java 8
  2. With Java 8 try with resources

Solution

  • You don't need to close the statement in this case, as Spring's JdbcTemplate will do that for you. In other words, this is a false positive of Sonar.

    As documented in the javadoc of PreparedStatementCreator.createPreparedStatement(Connection con) (emphasis mine):

    Create a statement in this connection. Allows implementations to use PreparedStatements. The JdbcTemplate will close the created statement.