0

I create this method to close statement and connection

 public void disconnetti(){
    try
    {
        if(stmt2!=null)
            stmt2.close();

        if(_conn!=null)
            _conn.close();

        System.out.println(stmt2);
        System.out.println(_conn);
    }
    catch(Exception e)
    {
        System.out.println("errore: "+ e);
    }
    finally
    {
        stmt2=null;
        _conn=null;
    }

    System.out.println(stmt2);
    System.out.println(_conn);
}

Inside the try catch,when i do the syso value of _conn, it is different from null.. why is possible?

Inside finally I assign manually value null at variable _conn

the methodology is right or am I wrong?

output

null
com.mysql.jdbc.JDBC4Connection@10a2ed93
null
null
  • always close _conn.close(); in finally block – Ashok Kumar N Feb 22 '19 at 10:52
  • 1
    In the `try` block you're only closing the connection, but not setting it to `null` these are 2 completly different things – Lino Feb 22 '19 at 10:53
  • Use try-with-resources to close connections, like shown here: https://stackoverflow.com/questions/22671697/try-try-with-resources-and-connection-statement-and-resultset-closing – Tom Feb 22 '19 at 10:55
  • Also if you happen to use java7 or above you can simply write `try(Statement s = stmt2; Connection c = _conn) {} catch(Exception e) {System.out.println("errore: "+ e);} finally {stmt2 = null; _conn = null; }` – Lino Feb 22 '19 at 10:56
  • @Lino with this try(Statement s = stmt2; Connection c = _conn) {} catch(Exception e) {System.out.println("errore: "+ e);} finally {stmt2 = null; _conn = null; } I close the connection too? –  Feb 22 '19 at 11:05
  • @cristianoronaldo yes, java will generate similar code like you've already written. But you don't have to do all those null checks and then closing the connection – Lino Feb 22 '19 at 11:11
  • @Lino ok Lino thanks a lot! –  Feb 22 '19 at 11:17

0 Answers0