我正在测试声纳以确保关闭数据库连接。
我正在使用嵌入式maven版本3.3.9从eclipse执行maven目标“sonar:sonar”。与sonarqube 6.2与sonar-java-plugin-4.10.0.10260.jar。
使用此代码
package servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class STestClosingResources extends HttpServlet{
private static final long serialVersionUID = 1L;
public final void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
Connection con = null;
ResultSet rsGet = null;
PreparedStatement psGet = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/testci");
con = ds.getConnection();
psGet = con.prepareStatement("SELECT * FROM TEST");
rsGet = psGet.executeQuery();
int counter = 0;
while (rsGet.next()) {
counter++;
System.err.println(counter);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rsGet != null) {
rsGet.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
rsGet = null;
try {
if (psGet != null) {
psGet.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
psGet = null;
}
}
}
我没想到这个问题:
在“finally”子句中关闭此“连接”。
为什么?
非常感谢
答案 0 :(得分:1)
负责分析Java代码并检测此问题的SonarJava分析器无法识别DataSource.getConnection
返回需要关闭的Connection
。我创建了修复它的票证https://jira.sonarsource.com/browse/SONARJAVA-2355