mybatis #与$占位符的区别


区别:

在sql中当传入的参数是字符型,则用#号会带上单引号,不会引起sql注入

在sql中当传入的参数是字符型,则用$号不会带上单引号,会引起sql注入

举个例子:

当传入的参数用于查询条件,尽量用#号,特殊情况可酌情使用#号或$号

mybatis代码:
select id,name from user where name = #{userName}
解析后的sql语句:
select id,name from user where name = '张三'

当传入的参数用于字段或表名,则必须使用$号,否则会报错(字段不存在或无效表名)

mybatis代码:
select id,${filedName} from ${userTable} 
解析后的sql语句:
select id,name from user  

错误的使用

mybatis代码:
select id,#{filedName} from #{userTable} 
解析后的sql语句:
select id,'name' from 'user'

虽然这2个占位符我们经常使用,当用错的时候还是很难发现的!!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM