${} 和 #{}的问题
<select id="selectPostOrder" resultMap="postOrderResultMap"> SELECT id, cid, lid, univalent, (account-nowaccount) as naccount, pclass, finaltime FROM postorder WHERE cid = #{id} and (account-nowaccount) > 0 and id not in ( select pid from optest ) and #{select} = '${input}' </select>
#{}
占位符:使用#{}
占位符来表示动态传入的参数,例如#{id}
和#{select}
。在执行 SQL 语句之前,MyBatis 会将#{}
占位符替换成相应的参数值,并进行参数类型转换和 SQL 注入防范。${}
表达式:使用${}
表达式来表示字符串拼接和替换。在执行 SQL 语句之前,MyBatis 会将${}
表达式替换成相应的字符串,并将其嵌入到 SQL 语句中。需要注意,在使用${}
表达式时,传入的参数值不会进行参数类型转换和 SQL 注入防范,因此需要特别小心避免 SQL 注入攻击。
例如,假设调用该查询语句时传入的参数为 id=1
、select='name'
和 input='北京'
,则执行的 SQL 语句为:
SELECT id, cid, lid, univalent, (account-nowaccount) as naccount, pclass, finaltime FROM postorder WHERE cid = 1 and (account-nowaccount) > 0 and id not in ( select pid from optest ) and 'name' = '北京'
其中,将 #{id}
和 #{select}
占位符替换成相应的参数值,并将 ${input}
表达式替换成字符串 '北京'
,并将其嵌入到 SQL 语句中。
需要注意的是,使用 ${}
表达式时,可能存在 SQL 注入攻击的风险,因此应该避免在 SQL 语句中嵌入动态生成的参数值,或者使用 MyBatis 提供的转义工具来对参数值进行转义,以提高应用安全性。