我遇到了一个问题,我使用单个参数的参数化查询可以正常运行,但是当插入多个参数时,它就不起作用了。
下面的方法可以正常工作:
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
是一个 Autowiring 的 JDBCTemplate,而 mapper
是一个 Autowiring 的 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 注入(inject),我不知道为什么这不起作用。我的语法有问题吗?还是我的做法完全错了?
最佳答案
你不能在类似的条件下使用 ?
那样的 '%?%'
。您需要删除 %
并将它们附加到您的字符串中。例如:
public List<Employee> getEmployeesBySearchCriteria(String criteria) {
String sql = "SELECT firstname, lastname FROM employees WHERE UPPER(firstname) LIKE UPPER(?)";
return getEmployeeList(sql, "%" + firstname + "%");
}
关于java - 使用 JDBC 模板的参数化 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25333102/