以Mybatis 为例,对常见的SQL 语句场景,构建安全的SQL 语句。
- 构建一般条件语句
<select id="normalSQL">
SELECT field_name FROM table_name WHERE 1 = 1
<if test="condition != null">
AND field_name = #{condtion}
</if>
</select>
- 构建like 条件语句
<select id="likeSQL">
SELECT field_name FROM table_name WHERE 1 = 1
<if test="condition != null">
AND field_name like CONCAT('%', #{condition}, '%')
</if>
</select>
- 构建in 条件语句
<select id="inSQL">
SELECT field_name FROM table_name WHERE 1 = 1
<if test="conditionArray != null">
field_name in
<foreach collection="conditionArray" item="item" open="("close=")" separator=",">
#{item}
</foreach>
</if>
</select>
4 .构建order by 语句
<select id="sortSQL">
SELECT field_name FROM table_name WHERE 1 = 1
<if test="sortField != null and sortBy null">
ORDER BY ${sortField} sortBy}
</if>
</select>
由于 MyBatis框架 order by 语句只能拼接,故需要研发人员在代码层控制传入 SQL 语句的参数,禁止将用户输入 据直接传SQL 语句 (参考代码如下:)
// Java
// 预先 order by 字段字典
Map fieldMap = new HashMap<String, String>();
fieldMap .put("key1", "name");
fieldMap .put("key2", "date");
// 获取用户提交的字典值
String req_sortField = request.getParameter("sortField");
// 预定义默认排序字段
String sortField = "name";
// 从预定义的字段 典中获取相对应值,若未到则使用默认
boolean result = fieldMap.containsKey(req_sortField);
if(result){
sortField = fieldMap.get(req_sortField).toString();
}
// 预定义默认排序规则
String sortBy = "asc";
if(req_sortBy.equals("desc") || req_sortBy.equals("asc"))){
sortBy = req_sortBy;
}