- 在Ibatis中我们使用SqlMap进行Sql查询时需要引用参数,在参数引用中遇到的符号 # 和 $ 之间的区分为,#可以进行预编译,进行类型匹配,而 $ 不进行数据类型匹配,例如:
select * from table where id = #id# ,其中如果字段id为字符型,那么#id#表示的就是'id'类型,如果id为整型,那么#id#就是id型。 select * from table where id = $id$ ,如果字段id为整型,Sql语句就不会出错,但是如果字段id为字符型,那么Sql语句应该写成 select * from table where id = '$id$'。
区别
- $ 的作用实际上是字符串拼接:
select * from $ tableName $
等效于:
StringBuffer sb = new StringBuffer(256);
sb.append("select * from ").append(tableName);
sb.toString();
- #用于变量替换
select * from table where id = #id#
等效于:
prepareStement = stmt.createPrepareStement
("select * from table where id = ?") ;
prepareStement.setString(1,'abc');
用法总结
- 对于变量部分, 应当使用 # ,这样可以有效的防止sql注入,并且 # 都是用到了prepareStement,这样对效率也有一定的提升。
- $ 只是简单的字符拼接而已,对于非变量部分, 那只能使用 $ , 实际上, 在很多场合,$ 也是有很多实际意义的 。
例如 :select * from $ tableName $ 对于不同的表执行统一的查询。 $只是字符串拼接, 所以要特别小心sql注入问题。 - 能同时使用#和$的时候最好用#。
转载注明出处:https://www.cnblogs.com/lcngu/p/5334993.html