Parameter index out of range参数越界的一些处理方法

Parameter index out of range的一些处理方法


最近项目开发的时候,出现了一个很怪异的BUG,Mybatis报Parameter index out of range异常,参数越界,就是说,参数数量和SQL语句的?占位符数量不一致,首先确定Mapper层的方法参数数量正确之后,对SQL语句进行检查

select * from student where sex = #{sex} and sname like '#{sname}%'
List<Student>	selectStudentByParam(int sex ,String sname);

我的Mapper层是只有2个参数,这个sql语句里也是2个“#”,百度得到,在MyBatis中,like语句需要这么写

select * from student where sex = #{sex} and sname like '${sname}%'

但是把#换成$符号会导致SQL注入问题,所以使用CONCAT方法,字符串拼接,所以有下面这种写法

select * from student where sex = #{sex} and sname like CONCAT(CONCAT('%',#{sname,jdbcType=VARCHAR}),'%') 

但是到头来,还是报这个异常…
此时我的MyBatis的这个sql语句是这样的

 <select id="selectStundentByPara"  resultType="com.bean.Student">
	-- select * from student where sex = #{sex} and sname like '${sname}%'
  select * from student where sex = #{sex} and sname like CONCAT(CONCAT('%',#{sname,jdbcType=VARCHAR}),'%') 
  </select>

还是一直报错一直报错…后来回去把xml文件里的下面这行这个注释删了…

-- select * from student where sex = #{sex} and sname like '${sname}%'

成功了…

我真不知道是啥情况,我的理解是,在MyBatis里对于SQL的注释,虽然在xml文件中使用 - - 注释,
但是 注释的语句里,如果有#{arg}或者${arg},MyBatis会把他认为是占位符"?",即使它已经被注释掉了,所以会认为有4个?占位符,而你只给了2个参数…

所以,虽然说代码写注释是个好习惯,但是遇到这种事,谁说得清呢?

  • 16
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值