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个占位符我们经常使用,当用错的时候还是很难发现的!!

原文地址:https://www.cnblogs.com/tianchao/p/11551422.html