Search code examples
javajdbc

What is the suitable way to close the database connection in Java?


I tried to close the DB connection.But had a bit of confusion, say

ResultSet rs = null 

Whether I have to it close by

rs.close();

Or

DatabaseUtil.closeResultSet(rs);

What is difference between those?


Solution

  • Those methods only close the ResultSet. You still have to close all Statement and Connection instances. I recommend doing so in a finally block. Something like,

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      conn = getConnection();
      stmt = conn.prepareStatement(sql);
      stmt.setString(1, "Hello"); 
      rs = stmt.executeQuery();
      while (rs.next()) {
        // ...
      }
    } catch (SQLException se) {
      se.printStackTrace();
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (stmt != null) {
        try {
          stmt.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (conn != null) {
        try {
          conn.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    

    If you use my Close utility the finally block could be,

    } finally {
      Close.close(rs, stmt, conn);
    }