Advertisement

javaweb复杂条件查询/多条件查询

阅读量:
在这里插入图片描述
复制代码
    <form class="form-inline" action="${pageContext.request.contextPath}/sel" method="post">
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" placeholder="输入查找的名字" name="sname" >
        </div>
        <div class="form-group">
            <label for="sex">性别</label>
            <input type="text" class="form-control" id="sex" placeholder="性别" name="sex" >
        </div>
    
        <button type="submit" class="btn btn-default">搜索</button>
    </form>

如图 进行复合条件查询时候
首先 在servlet (url为sel)中接收 表单数据

request.setCharacterEncoding("utf-8");
request.getParameterMap().//用于 解析 表单数据
解析出 一个对象。

遍历MAP 得到 相应的表单信息 如例: sname 和 sex

进行JDBC操作

在涉及复合条件查询的情况下,由于sname和sex字段都可能为空的原因,必须将SQL分解为动态构建的形式。

String sql = "select * from t_student(表名) where 1=1";
ArrayList arr = new ArrayList();
if (sName != null && !"".equals(sName)) {
sql += "and sName = ?";
arr.add(sName);
}
// 注意这里 sName不能等于null也不能为空字符串 因此在if条件中包含两个限定条件:sName != null && !"".equals(sName)
// 同理 sex也需要进行相同的操作
if (sex != null && !"".equals(sex)) {
sql += "and sex = ?";
arr.add(sex);
}
最后使用Query对象执行sql语句:
IQueryQuery = new JDBCTemplate();
IQueryQuery.Query(sql, new BeanPropertyRowMapper<String[][]>(T.class), arr.toArray(new String[0])); //传入arr数组;

全部评论 (0)

还没有任何评论哟~