先上结论
#和 $区别总结
-
#使用 ?在sql语句中做占位的, 使用PreparedStatement执行sql,效率高,能够避免sql注入,更安全。
-
#{}一般作为列的值使用,在等号的右边,#{}位置的值和数据类型有关
-
$不使用占位符,是字符串连接方式,使用Statement对象执行sql,效率低,有sql注入风险,缺乏安全性。
-
${}数据是原样是用的,不区分数据类型,常用作表名或者列名
#占位符,告诉 mybatis 使用实际的参数值代替。并使用 PrepareStatement 对象执行 sql 语句, #{…}代替
sql 语句的“?”
mapper 文件
<select id="selectById" resultType="com.nefu.entity.Student">
select id,name,email,age from student where id=#{studentId}
</select>
转为 MyBatis 的执行是:
String sql=” select id,name,email,age from student where id=?”;
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,1005);
解释:
where id=? 就是 where id=#{studentId} ps.setInt(1,1005) , 1005 会替换掉 #{studentId}
$ 字符串替换,告诉 mybatis 使用 $ 包含的“字符串”替换所在位置。使用 Statement 把 sql 语句和${}的内容连接起来。主要用在替换表名,列名,不同列排序等操作。