Skip to content
Advertisement

Should I close the prepared statement passed as parameter?

I am aware that we should not reuse prepared statement or use try-with-resource in java. But what should I do with prepared statement passed as parameter? Should I close it too?

For example:

private void somemethod(PreparedStatement pStmt1, PreparedStatement pStmt2 ) 
{
    int nCount = 0;
    try
    {
        pStmt1.setString (1,"something");
        pStmt1.setInt(2, 1);
        nCount = pStmt1.executeUpdate();
        pStmt1.clearParameters();
        
        if (nCount == 0)
        {
            pStmt2.setInt(1, 1);
            pStmt2.setString(2, "something");
            
            pStmt2.executeUpdate();
            pStmt2.clearParameters();
        }
        
    }
    catch (Exception ex)
    {
        LOGGER.log(e);
    }   
    finally {
    //here should I close these parameters of prepared statements? 
    //Even though I do not close them the sonar is not giving blocker to close them. 
    //So I am curious to know the reality. Please help. Thank you
         pStmt1.close();                
         pStmt2.close();                
    }
    
 }

Advertisement

Answer

The way I see it is as follows:

In your code somemethod is not the owner of those prepared statements that were passed to it. It didn’t create them, thefore it should not be responsible for its lifecycle (like closing them).

The same code that created them should also be responsible for closing them. somemethod was just “leased” those prepared statement, it should treat them with respect.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement