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

后端 未结 7 1759
盖世英雄少女心
盖世英雄少女心 2020-12-20 04:15

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.c         


        
7条回答
  •  盖世英雄少女心
    2020-12-20 04:55

    Normal code would look like this:

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    try {
      connection = getConnection();
      stmt = connection.prepareStatement("...");
    
      stmt.setString(":foobar", "Foobar");
      rs = stmt.execute ... ; // I don't remember the method return ResultSet
    
      while (rs.next()) {
        ...
      }
    
      stmt.setString(":foobar", "Barfoo");
      rs2 = stmt.execute ... ; 
    
    
    } finally {
      if (null != rs2) try {rs2.close();} catch (Exception e)
      if (null != rs) try {rs.close();} catch (Exception e) {...}
      if (null != stmt) try {stmt.close();} catch (Exception e) {...}
      if (null != connection) try {connection.close();} catch (Exception e) {...}
    }
    

    Or, in Java 7, using the try-with-resources (the previous code is almost the same):

    try (Connection connection = getConnection();
         PreparedStatement stmt = connection.prepareStatement("...")) {
    
      stmt.setString(":foobar", "Foobar");
      try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            ...
        }
      }
      stmt.setString(":foobar", "Barfoo");
      try (ResultSet rs2 = stmt.executeQuery()) {
        while (rs2.next()) {
            ...
        }
      }
    }
    

    The difference is simple:

    • you close the ResultSet - to free the resource associated. In this example, I used a PreparedStatement: you could have parameters, hence different ResultSet. Because it takes memory and resources, you need to close them after you are done with them, otherwise that the garbage collector that will do that, and it will do it only to reclaim memory.
    • you close the PreparedStatement or Statement when you no longer need it. Closing the statement close the associated ResultSet.
    • you close the Connection when you no longer need it. Closing the connection close the Statements (and their ResultSet).

    Depending on your need (eg: a batch versus a web server), you might not have to close the connection at it would be when Java exit, but it is better to free resources when you no longer need them (whether them being JDBC resources or file resources ...).

提交回复
热议问题