mybatis plus报错问题:Caused by java.sql.SQLException Parameter index out of range (5 number of param

报错信息

Caused by java.sql.SQLException Parameter index out of range (5 number of param

问题描述:

在mapper中的selected中希望执行时间的过滤,代码如下

"<when test='startDate!=null'>",
" and foal_date &gt;= '#{startDate}' ",
"</when>",
"<when test='endDate!=null'>",
" and foal_date &lt;= '#{endDate}' ",
"</when>",

报错详情

Caused by: java.sql.SQLException: Parameter index out of range (5 > number of parameters, which is 4).
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.17.jar:8.0.17]
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.17.jar:8.0.17]
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.17.jar:8.0.17]
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.17.jar:8.0.17]

网上搜索问题原因:
动态sql语句中where标签使用的时候,由于在select标签中按快捷键添加了注释,导致出现错误,-- 只要把注释去掉或者改成正确的注释格式就可以成功运行。
于是检查了之前写过的没有问题的时间过滤代码,比对了下发现:

"<when test='startDate != null'>",
" and create_time  &gt; '${startDate}' ",//注意看,此处是$,问题的原因就是加了‘’之后导致运行时把tnd的#认为是一个注释了!
"</when>",
"<when test='endDate != null'>",
" and create_time &lt; '${endDate}' ",
"</when>",

总结

:需要对拼接sql的#{}和%{}的用法要更加熟悉
网上找到的相关建议
#{} 和 ${} 在使用中的技巧和建议

(1)不论是单个参数,还是多个参数,一律都建议使用注解@Param("")

(2)能用 #{} 的地方就用 #{},不用或少用 ${}

(3)表名作参数时,必须用 ${}。如:select * from ${tableName}

(4)order by 时,必须用 ${}。如:select * from t_user order by ${columnName}

(5)使用 ${} 时,要注意何时加或不加单引号,即 和 ′ {} 和 ' {}’

原文链接:https://blog.csdn.net/weixin_40922494/article/details/118757230

个人总结

在涉及到时间的过滤时,以及传入字段用于order by 等务必使用${}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐州蔡徐坤

又要到饭了兄弟们

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值