使用JDBC模板的java参数化sql查询
我遇到了这样一个问题:使用单个参数的参数化查询可以正常运行,但是当插入多个参数时,它就不起作用了
以下方法效果良好:
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
是一个自动连接的行映射器
但是,这种方法根本不起作用:
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注入,我不明白为什么这不起作用。我的语法有问题吗?还是我完全错了
# 1 楼答案
不能在类似的条件下使用
?
这样的'%?%'
。您需要删除%
并将它们附加到字符串中。例如: