【发布时间】:2019-06-17 08:11:49
【问题描述】:
我正在尝试使用 try/finally 关闭我的结果集、连接和语句,但 Sonar 似乎不喜欢它。我在做什么错误,为什么他们不关闭?谢谢。
public static List<String> findByName(String firstName, String lastName) throws SQLException {
/*Connects to table and contexts a statement to this connection. Creates the appropriate statement (query)
according to the first name and last name nulls, builds an array from the ResultSet that is created.*/
List<String> nameList = new ArrayList();
String query;
Connection conn = null;
Statement preparedStatement = null;
ResultSet allNames = null;
try {
conn = DriverManager.getConnection(getHost(), getuName(), getuPass());
preparedStatement = conn.createStatement();
if (firstName == null && lastName == null) {
query = "SELECT * FROM person_c";
} else if (firstName == null) {
query = "SELECT * FROM person_c WHERE LAST_NAME= '" + lastName + "'";
} else if (lastName == null) {
query = "SELECT * FROM person_c where FIRST_NAME= '" + firstName + "'";
} else {
query = "SELECT * FROM person_c where FIRST_NAME = '" + firstName + "'" + "AND LAST_NAME= '" + lastName + "'";
}
allNames = preparedStatement.executeQuery(query);
while (allNames.next()) {
nameList.add(allNames.getString("FIRST_NAME") + " " + allNames.getString("LAST_NAME"));
}
} finally {
if (allNames != null) allNames.close();
if (preparedStatement!=null) preparedStatement.close();
if (conn!=null) conn.close();
}
return nameList;
}
【问题讨论】:
-
似乎不喜欢它。 - 这不是很有技术含量吗?错误是什么?
-
从安全方面我会说这个 sql 查询容易受到 sql 注入的影响。不要使用
"SELECT * FROM person_c WHERE LAST_NAME= '" + lastName + "'";。请改用参数化语句。 More Information to SQL Injections -
谢谢 MapReduce - 我以后会记住的。目前我们只是在做练习,因为我是学徒。我已经完成了代码,但正在整理边缘。
-
@MapReduce - OMG,我怎么会错过这些查询中有字符串 concat 的事实?!