jain626
jain626

Reputation: 1

Static Code Analysis Comments

I have scanned my code with static code analyzer and got Unreleased Resource: Database error. I am closing all the db connection below is the snap shot of my code.

public String methodInDAO(Bean bean) throws SQLException ,Exception
{

    Session session = null;
    Connection connection = null;
    ResultSet resultSet1 = null;
    CallableStatement callableStatement = null;

    try {
         connection = dataSource.getConnection();
         callableStatement = connection.prepareCall(query);
         resultSet1 = callableStatement.execute();
        //code operations
   } finally {
        if(null != callableStatement)
            callableStatement.close();

        resultSet1 = null;
        callableStatement = null;

        if(null != connection)
            connection.close();

        if (null != session)
            session.close();

    }

    return returnOutput;
}

All the thrown exceptions are handled at service layer. Could anyone suggest where is datasource not released ?

Upvotes: 0

Views: 237

Answers (1)

user1907906
user1907906

Reputation:

If your JDBC driver supports JDBC 4.1, you can use try-with-resources.

try (connection = dataSource.getConnection();
     callableStatement = connection.prepareCall(query)) {
  results = callableStatement.execute();
  // code operations
}

The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement

was added to JDBC 4.1.

Upvotes: 3

Related Questions