繁体   English   中英

使用JDBC模板进行参数化的sql查询

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM