您的位置:首页 > 职场人生

mybatis中# 和$ 符号的区别

2017-06-27 00:00 267 查看
摘要: 记得在面试中有被问到,查询了一下万能的互联网,做一个总结

#{} 和${}都是在sql语句当中使用

区别在于

1.sql解析语句的时候会在#{}传入的数据加引号,而不会在${}加引号(显示的是原来的sql)

即:

#{} select * from table1 where id=#{id} -->select * from table1 where id='2'

${} select * from table1 where id=${id} -->select * from table1 where id=2

2.也正是如此, #{}能够很大程度防止sql注入,而${}是元语句输出

3.$方式一般用于传入数据库对象,例如传入表名.一般能用#的就别用$

MyBatis排序时使用order by 动态参数时需要注意,用$而不是#

如:

select * from ${tableName} order by ${id} 这里需要传入表名和按照哪个列进行排序

加入传入table1、id 则语句为:select * from table1 order by id

如果是使用#{} 则变成了select * from 'table1' order by 'id' 我们知道这样就不对了。

参考借鉴:

http://blog.csdn.net/kobi521/article/details/16941403

http://www.cnblogs.com/teach/p/5685545.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息