我遇到了一个问题,我的参数化查询只有一个参数运行正常,但是当插入多个参数时,它不起作用。
以下方法可以正常工作:
public Employee getEmployeeByID(int id) {
String sql = "SELECT firstname, lastname FROM employees WHERE employeeID = ?";
List<Employee> list = getEmployeeList(sql, id);
if (list.isEmpty()) {
return null;
}
return list.get(0);
}
这是getEmployeeList,它取决于:
private List<Employee> getEmployeeList(String sql, Object... params) {
List<Employee> list = new ArrayList<Employee>();
for (Object o : template.query(sql, mapper, params)) {
list.add((Employee) o);
}
return list;
}
请注意,template
是自动装配的JDBCTemplate,mapper
是自动装配的RowMapper。
但是,这种方法根本不起作用:
public List<Employee> getEmployeesBySearchCriteria(String criteria) {
//business logic that determines the values
//of Strings firstname, lastname, and keyword...
String sql = "SELECT firstname, lastname FROM employees WHERE UPPER(firstname) LIKE UPPER('%?%') ? UPPER(lastname) LIKE UPPER('%?%')";
return getEmployeeList(sql, firstname, keyword, lastname);
}
我收到以下错误:
java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
我明白我可以手动将每个字符串附加到sql语句中,但是我关注sql注入,我无法弄清楚为什么这不起作用。我的语法有问题吗?或者我是否完全错了?
答案 0 :(得分:3)
您不能在类似条件下使用?
'%?%'
。您需要删除%
并将它们附加到您的字符串中。例如:
public List<Employee> getEmployeesBySearchCriteria(String criteria) {
String sql = "SELECT firstname, lastname FROM employees WHERE UPPER(firstname) LIKE UPPER(?)";
return getEmployeeList(sql, "%" + firstname + "%");
}