Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

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


[8]ページ先頭

©2009-2025 Movatter.jp