JSP + SQL(使用Like)

时间:2015-09-29 11:55:16

标签: java sql jsp servlets sql-like

JSP文件:

<form action="PatientsController?cmd=search" method="post">
   <input type="text" name="search" placeholder="Search here.."
                        class="form-control text-box single-line">


   <select name="select">
        <option value="id">Id</option>
        <option value="name">Name</option>
        <option value="address">Address</option>
        <option value="cpf">Cpf</option>
        <option value="phone">Phone</option>
        <option value="birthDate">Birth Date</option>
        <option value="gender">Gender</option>
    </select>
</form>

的Servlet

List<Patient> list = new PatientDao().indexFilter(
        request.getParameter("select"),
        request.getParameter("search"));
request.setAttribute("new", list);
request.getRequestDispatcher("Index.jsp")
        .forward(request, response);

PatientDAO:

public List<Patient> indexFilter(String attribute, String condition)
        throws Exception {
    open();

    ps = con.prepareStatement("SELECT * FROM patients WHERE ? like ? ORDER BY id");
    ps.setString(1, attribute);
    ps.setString(2, "%" + condition + "%");
    rs = ps.executeQuery();

    List<Patient> list = new ArrayList<Patient>();

    while (rs.next())
        list.add(newPatientSetted());

    ps.close();

    close();
    return list;
}

private Patient newPatientSetted() throws Exception {
    return new Patient(rs.getInt(1), rs.getString(2), rs.getString(3),
            rs.getString(4), rs.getString(5), rs.getDate(6), rs
                    .getString(7).equals("M") ? Gender.M : Gender.F);
}

所以,我有一个问题,我不知道但是查询没有返回任何内容(我在DAO中进行了调试,并且它不会在while循环中加入 - 换句话说,结果集不会有下一个()),我做错了什么?如果我删除&#34;?&#34;之后&#34;哪里&#34;并手动放置一个属性LIKE运算符。

2 个答案:

答案 0 :(得分:0)

只有具有感知“值”的地方才允许使用SQL参数。被拒绝代替桌子或柱子。

 "SELECT * FROM patients WHERE ? like ? ORDER BY id"  -- bad, field 'substitution' is not alowed

 "SELECT * FROM ? WHERE id like ? ORDER BY id"  -- bad, column is not alowed

 "SELECT * FROM patients WHERE Name like ? ORDER BY id"  -- OK, 

背景。让我们想象一下sql server准备查询tu实现更高的速度。无法使用未知列或字段进行优化。它的唯一形象是更好地理解。

严格:被标准拒绝。

编辑:扩展aswer,如何实现目标:

 String qry = "SELECT * FROM patients WHERE "+attribute +" like ? ORDER BY id";
 ps = con.prepareStatement(qry);
    ps.setString(1, "%" + condition + "%");
    rs = ps.executeQuery();

答案 1 :(得分:0)

准备语句时,数据库会构造一个执行计划,如果表或列不存在,则无法执行该计划。换句话说,placehodlers只能用于而不能用于对象名称或保留字。在这种情况下,您必须依赖Java来构造字符串

String sql = "SELECT * FROM patients WHERE "+attribute+" like ? ORDER BY id ";
ps = con.prepareStatement(sql);
ps.setString(1, "%" + condition + "%");
rs = ps.executeQuery();