Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between connection.close() and connection= null

Tags:

jdbc

If I explicitly close the connection by calling close() on connection object, i have set connection object to null. What is difference in close() and null on connection object? If i close connection ,still connection object maintained in connection pool? for e.g.

Connection dbConnection=null;
PreparedStatement preparedStatement = null;
ResultSet rs;
  try {
           Connection dbConnection= DriverManager.getConnection("jdbc:hsqldb:file:test5","sa", "");
           ...........
           ...........
           dbConnection.close();
           dbConnection=null;
           } catch (Exception e) {
        LOGGER.error("Exception Occured while fetching All record:Item details start method "
                + e.getMessage());
    } finally {

        try
        {
            if (rs!=null)
            {
                rs.close();
                rs=null;
            }

        }
        catch(SQLException e)
        {
            LOGGER.error(RESULTSETCLOSEEXCEPTION
                    + e.getMessage());
        }

        try {
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement=null;
            }
        } catch (SQLException e) {
            LOGGER.error(STATEMENTCLOSEEXCEPTION
                    + e.getMessage());
        }
        try {
            if (dbConnection != null) {
                dbConnection.close();
                dbConnection=null;
            }
        } catch (SQLException e) {
            LOGGER.error(CONNECTIONCLOSEEXCEPTION
                    + e.getMessage());
        }
    }

Is above code is correct way to close connection, prepared statement and resultset?

like image 298
Viraj Dhamal Avatar asked Aug 24 '26 01:08

Viraj Dhamal


1 Answers

From the documentation.

close()
Releases this Connection object's database and JDBC resources immediately instead of
waiting for them to be automatically released.
like image 174
unnu Avatar answered Aug 26 '26 22:08

unnu