Balachandar Thangavel
Balachandar Thangavel

Reputation: 67

Resultset is never closed - Sonarqube analysis

In our code , we have closed the results sets in finally block still the sonar shows that it is never closed. Kindly help.Here we have created connection using Spring datasource utils and using the same have released the connections to pool.

try {
  con = DataSourceUtils.getConnection(dataSource); // connection to database using spring
  stmt = con.createStatement();
  rs = stmt.executeQuery("<>");
  .
  .
}
catch (Exception e) {
}
finally {
  if (stmt != null && !stmt.isClosed()) {
    stmt.close();
  }
  if (rs != null && !rs.isClosed()) {
    rs.close();
  }
  if (con != null) {
    DataSourceUtils.releaseConnection(con, dataSource);
  }
}

Upvotes: 0

Views: 1876

Answers (3)

Balachandar Thangavel
Balachandar Thangavel

Reputation: 67

Finally I found the reason why Sonar is throwing the error even though we have closed the resources.

the Sonar expects each resource to be closed separately in separate try catch. The reason behind sis if once resource closure causes issue, others might be left open too.

Like this,

finally{
try{
if(resultset!=null){
resultset.close();
}
catch(SQLException e){
---
---
}
if(connection!=null){
connection.close();
}
catch(SQLException e){
---
---
}
}

Again in the above code, please add logger.error in exception to avoid another error from Sonar !! ! :) logger.error("", e);

Upvotes: 0

Andrew S
Andrew S

Reputation: 2756

It's possible for

stmt.close();

to throw a SQLException. If that happens then

rs.close();

will never be executed. As others have suggested, consider using try with resource.

Upvotes: 3

dpr
dpr

Reputation: 10964

You should use the try-with-resource statement to cleanup your code and ensure proper resource handling:

try (final Connection con = DataSourceUtils.getConnection(dataSource); // connection to database using spring
    final Statement stmt = con.createStatement();
    final ResultSet rs = stmt.executeQuery("<>");) {
    ...
} catch (Exception e) {
   // handle Exceptions here
}

Upvotes: 1

Related Questions