Potential database resource leak¶
ID: java/database-resource-leakKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - performance - resources - external/cwe/cwe-404 - external/cwe/cwe-772Query suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
A database resource in thejava.sql package that is opened but not closed may cause a resource leak and ultimately resource exhaustion.
Recommendation¶
Ensure that the resource is always closed to avoid a resource leak. Note that, because of exceptions, it is safest to close a resource in afinally block.
For Java 7 or later, the recommended way to close resources that implementjava.lang.AutoCloseable is to declare them within atry-with-resources statement, so that they are closed implicitly.
Example¶
In the following example, the resourcesstmt andrs are opened but not closed.
publicclassCloseSql{publicstaticvoidrunQuery(Connectioncon,Stringquery)throwsSQLException{Statementstmt=con.createStatement();ResultSetrs=stmt.executeQuery(query);while(rs.next()){// process result set}}}
In the following example, the resourcesstmt andrs are declared within atry-with-resources block and are thus closed implicitly.
publicclassCloseSqlGood{publicstaticvoidrunQuery(Connectioncon,Stringquery)throwsSQLException{try(Statementstmt=con.createStatement();ResultSetrs=stmt.executeQuery(query)){while(rs.next()){// process result set}}}}
Note that theConnection that is passed into the method is a long-lived object that was created elsewhere and therefore need not be closed locally. It should instead be closed by the code that created it or by a server shutdown procedure, as appropriate.
References¶
IBM developerWorks:Java theory and practice: Good housekeeping practices.
The Java Tutorials:The try-with-resources Statement.
Common Weakness Enumeration:CWE-404.
Common Weakness Enumeration:CWE-772.