0

I'm using sonarqube to analyse code to check some of it problems. One of the recommendations that the tool has given me is, as the title says, "Use try-with-resources or close this "Statement" in a "finally" clause". I don't know what it is referring to, even after checking some notes. The piece of code is this:

try {
    sentencia = conexion.createStatement();
    sentencia.executeUpdate(consulta);
    dispose();
} catch (SQLException e1) {
    JOptionPane.showMessageDialog(this, "No se puede insertar la cita", "Error", JOptionPane.ERROR_MESSAGE);
    LOGGER.log(Level.SEVERE,"Excepcion provocada",e1);
}

How can I fix this so it could be express as Sonarqube recommends me?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    You are not calling `close()` on the Statement object `sentencia`. One way to do that is to use try with resources. Or you can call it yourself – ernest_k Nov 01 '20 at 18:57
  • 1
    You created a statement, you need to close it once you're done with it. – Mark Rotteveel Nov 01 '20 at 18:57
  • 1
    BTW: The fact that `sentencia` is not declared in this block might be an indication that you're scoping your variables or fields too broad. – Mark Rotteveel Nov 01 '20 at 19:01
  • Please search on "java try-with-resources". This automatically closes the resources after the try. You can also use a finally clause instead, "java try catch finally". – NomadMaker Nov 01 '20 at 22:32

1 Answers1

0

Something like this should help!

void test(){
        Statement sentencia;
        Connection conexion;

        try {
            sentencia = conexion.createStatement();
            sentencia.executeUpdate(consulta);
            dispose();
        } catch (SQLException e1) {
            JOptionPane.showMessageDialog(this, "No se puede insertar la cita", "Error", JOptionPane.ERROR_MESSAGE);
            LOGGER.log(Level.SEVERE,"Excepcion provocada",e1);
        } finally {
            if(null != sentencia){
                sentencia.close();
            }
        }
    }