[英]Parameterized sql queries with JDBC template
我遇到了一個問題,我的參數化查詢與單個參數運行良好,但插入多個參數時,它不起作用。
以下方法工作正常:
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注入,我無法弄清楚為什么這不起作用。 我的語法有問題嗎? 或者我是否完全錯了?
你不能用?
就像那個'%?%'
一樣。 您需要刪除%
並將它們附加到您的字符串。 例如 :
public List<Employee> getEmployeesBySearchCriteria(String criteria) {
String sql = "SELECT firstname, lastname FROM employees WHERE UPPER(firstname) LIKE UPPER(?)";
return getEmployeeList(sql, "%" + firstname + "%");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.