中三A105论坛
请选择 进入手机版 | 继续访问电脑版

注册 登录
查看: 781|回复: 0

Mybatis 中$与#的区别

[复制链接]

105

主题

119

帖子

553

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
553
发表于 2019-4-22 20:54:00 | 显示全部楼层 |阅读模式
1 #是将传入的值当做字符串的形式,eg:select id,name,age from student where id =#{id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id ='1'.
2 $是将传入的数据直接显示生成sql语句,eg:select id,name,age from student where id =${id},当前端把id值1,传入到后台的时候,就相当于 select id,name,age from student where id = 1.
3 使用#可以很大程度上防止sql注入。(语句的拼接)
4 但是如果使用在order by 中就需要使用 $.
5 在大多数情况下还是经常使用#,但在不同情况下必须使用$.
我觉得#与<span class="MathJax" id="MathJax-Element-1-Frame" tabindex="0" data-mathml="&#x7684;&#x533A;&#x522B;&#x6700;&#x5927;&#x5728;&#x4E8E;&#xFF1A;#{}&#xA0;&#x4F20;&#x5165;&#x503C;&#x65F6;&#xFF0C;sql&#x89E3;&#x6790;&#x65F6;&#xFF0C;&#x53C2;&#x6570;&#x662F;&#x5E26;&#x5F15;&#x53F7;&#x7684;&#xFF0C;&#x800C;" role="presentation" style="display: inline; line-height: 1.5; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; position: relative;">的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而的区别最大在于:#{} 传入值时,sql解析时,参数是带引号的,而{}穿入值,sql解析时,参数是不带引号的。
一 : 理解mybatis中 $与#
    在mybatis中的$与#都是在sql中动态的传入参数。
    eg:select id,name,age from student where name=#{name}  这个name是动态的,可变的。当你传入什么样的值,就会根据你传入的值执行sql语句。
二:使用$与#
   #{}: 解析为一个 JDBC 预编译语句(prepared statement)的参数标记符,一个 #{ } 被解析为一个参数占位符 。
   ${}: 仅仅为一个纯碎的 string 替换,在动态 SQL 解析阶段将会进行变量替换。
  name-->cy
eg:  select id,name,age from student where name=#{name}   -- name='cy'
       select id,name,age from student where name=${name}    -- name=cy


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回列表 返回顶部