Mybatis中的#与$的区别

一、对比场景

场景:数据库分表时,需要将分表的表序号传入的sql中。

SpringBoot中使用注解如下:

@Insert("insert into collect_#{tblNum}(id,user_id,resource_id,resource_name,author,album,resource_type,create_time,update_time)" +
            " values (uuid(),#{userId},#{collect.resourceId},#{collect.resourceName},#{collect.author}," +
            "#{collect.album},#{collect.resourceType},#{time},#{time})")  

报错提示找不到表 

2018-06-20 08:55:04.398 ERROR [http-nio-9902-exec-2][CollectController.java:69] - org.springframework.jdbc.UncategorizedSQLException: 
### Error updating database.  Cause: java.sql.SQLException: sql injection violation, syntax error: syntax error, error in :'into collect_?(id,user_id,r',expect QUES, actual QUES collect_ : insert into collect_?(id,user_id,resource_id,resource_name,author,album,resource_type,create_time,update_time) values (uuid(),?,?,?,?,?,?,?,?)
### SQL: insert into collect_?(id,user_id,resource_id,resource_name,author,album,resource_type,create_time,update_time) values (uuid(),?,?,?,?,?,?,?,?)
### Cause: java.sql.SQLException: sql injection violation, syntax error: syntax error, error in :'into collect_?(id,user_id,r',expect QUES, actual QUES collect_ : insert into collect_?(id,user_id,resource_id,resource_name,author,album,resource_type,create_time,update_time) values (uuid(),?,?,?,?,?,?,?,?)
; uncategorized SQLException for SQL []; SQL state [null]; error code [0]; sql injection violation, syntax error: syntax error, error in :'into collect_?(id,user_id,r',expect QUES, actual QUES r1_mini_collect_ : insert into collect_?(id,user_id,resource_id,resource_name,author,album,resource_type,create_time,update_time) values (uuid(),?,?,?,?,?,?,?,?); nested exception is java.sql.SQLException: sql injection violation, syntax error: syntax error, error in :'into r1_mini_collect_?(id,user_id,r',expect QUES, actual QUES collect_ : insert into collect_?(id,user_id,resource_id,resource_name,author,album,resource_type,create_time,update_time) values (uuid(),?,?,?,?,?,?,?,?)

 解决办法:collect_#{tblNum}修改为collect_${tblNum}即可解决问题。

二、#与$的区别

Mybatis中的#与$的区别如下

  1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号,所以我们在插入字符串的时候不需要加''或者“”,因为这个是#帮我们加上的。如:order by #{user_id},如果传入的值是123,那么解析成sql时的值为order by "123", 如果传入的值是id,则解析成的sql为order by "id".
  2. $将传入的数据直接显示生成在sql中,如:order by ${user_id},如果传入的值是123,那么解析成sql时的值为order by 123,  如果传入的值是id,则解析成的sql为order by id。
  3. #方式能够很大程度防止sql注入,$方式无法防止Sql注入。
  4. $方式一般用于传入数据库对象,例如传入表名。
  5. 一般能用#的就别用$. 。

 

参考文章:

https://blog.csdn.net/downkang/article/details/12499197

转载于:https://www.cnblogs.com/lingyejun/p/9201981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值