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

后端 未结 7 1744
盖世英雄少女心
盖世英雄少女心 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)
        {
        }
    

提交回复
热议问题