Purpose

This page provides information about the quality rule - Close database resources ASAP.

Applicable in CAST Version
Release
Yes/No
8.3.x(tick)
Applicable RDBMS
RDBMS
Yes/No
CSS(tick)
Details

If you have closed the open connections using a method call containing the connection.close then it is expected to have this as violation though it may seem that the connection is closed for you.

Example -

public static void main(String [] args) {
    Connection con = null;
    com.mysql.jdbc.jdbc2.optional.MysqlDataSource datasource1 = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    con = datasource1.getConnection();
 
    close_connections(con);
}
 
public static void close_connections(Connection con1) {
    con1.close();
}


The analyzer is designed in such a way to violate such code as the method close_connections which is calling the close connection may change and then you will not be sure that the connection is actually closed. This is not a good programming practice and the connection.close(); should appear in the same block. So this is expected behavior to have the violation.

Below is another scenario in which the violation is coming up.

The violation is raised for the following sample source code:

try {
            int index = 0;
        	prepareStmt = connection.prepareStatement(CetsQueryConstants.DELETE_COMNT_FILE_ASSOC_BY_AGMNT_DOC_ID);
            prepareStmt.setLong(++index, docId);
            prepareStmt.setLong(++index, agreementKey);
            deleteCount = prepareStmt.executeUpdate();
        } catch (SQLException sqlException) {
            throw sqlException;
        } 
		finally {
			try {
				if (connection != null)
				{
					connection.close();
				}
			    cleanObjects(prepareStmt, rset);
            
			}

To fix the problem, proceed as follows:

 In order to not get this violation, the connection should be explicitly closed. Below is the sample source code on how to close the connection so that the violation is not raised: 

try {
            int index = 0;
        	prepareStmt = connection.prepareStatement(CetsQueryConstants.DELETE_COMNT_FILE_ASSOC_BY_AGMNT_DOC_ID);
            prepareStmt.setLong(++index, docId);
            prepareStmt.setLong(++index, agreementKey);
            deleteCount = prepareStmt.executeUpdate();
        } catch (SQLException sqlException) {
            throw sqlException;
        } 
		finally {
			try {
				if (connection != null)
				{
					prepareStmt.close();
					connection.close();
				}
			    cleanObjects(prepareStmt, rset);
            
			}

prepareStmt.close(); is the way to close the connection completely and now when you run analysis+snapshot again, the violation will not be raised.

 
However, if you have a different opinion i.e. you are sure that the method is closing the connection, then you can exclude the violation for those objects.

Notes/comments

Ticket #5217

Related Pages