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

后端 未结 7 1737
盖世英雄少女心
盖世英雄少女心 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:42

    Closing the resultSet doesn't close the database connection. We should close the connection as like given below. Before closing the connection you should close the other instance like ResultSet, PreparedStatement and Statement instances.

    for example

     Connection con = DBUtils.getConnection();
     ....
     PreparedStatemet pstmt = con.getPreparedStatement();
     ResultSet rs = pstmt.execute();
    
     while(rs.next())
     {
     }
    

    // Once you done the ResultSet... It's time to close/release the Instances.

        if (resultSet != null) {
        try {
        resultSet.close();
        resultSet = null;
        } catch (SQLException e) {
          // ignore the exceptions.
        }
        }
    
        // Close the Prepared Statement
        if(theStatement != null)
        {
        try
        {
        theStatement.close();
        theStatement = null;
        }
        catch(Exception ignored)
        {
        }
    
    // Close the Connection
        if(theConnection != null)
        {
        try
        {
        theConnection.close();
        theConnection = null;
        }
        catch(Exception ignored)
        {
        }
    
    0 讨论(0)
  • 2020-12-20 04:44

    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);
    }
    
    0 讨论(0)
  • 2020-12-20 04:49

    The jdbc api tells us that closing the connection will close result sets and statements. Closing statements will close the result set. But I always close every result set and every statement myself because I ran into problems not doing so. Just use the close method provided by you result set, statement and connection.

    0 讨论(0)
  • 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 ...).

    0 讨论(0)
  • 2020-12-20 04:58

    I think the best way is do everything within a try-with-resources

    try(conn=openConnection()){
      try(rs=conn.getResultSet()){
      }
    }
    

    So that you be entirely sure the resources will be properly closed at the end.

    0 讨论(0)
  • 2020-12-20 04:59

    Both ways works, but I prefer the first rs.close(); , without forgeting to check if rs is not null and to enclose your call by a try..catch statement so you have to close your connection in the finaly block even if Java7 close all for you.

    check Java / JDBC: Best design pattern to close database connection when exception occurs

    0 讨论(0)
提交回复
热议问题