$与#区别

来源:互联网 发布:馆陶县行知教育集团 编辑:程序博客网 时间:2024/06/10 20:30

比如说一条SQL语句

select * from user where id=${id} and username=#{username}

在经过编译后,得到如下语句

select * from user where id=2 and username=?

通过以上SQL语句看出,经过编译后

如果是#{}的形式是编译成?,而如果${}是编译成直接的数据。


区别:

#{}: 是以预编译的形式,将参数设置到SQL语句中;PreparedStatement:防止SQL注入

${}: 取出的值直接拼装在SQL语句中;会有安全问题

大多数情况下,我们去参数的值都应该使用#{}


原先jdbc不支持点位符的地方我们就可以使用${}去取值(不能出现问号的地方)

比如分表;按照年份分表拆分

select * from ${year}_salary where xxx;

select * from employee order by ${f_name};

而出现问题的地方,即占位符出现的地方

select * from user where username=?;使用#{}

select * from user where username=#{username};