报错信息
Caused by java.sql.SQLException Parameter index out of range (5 number of param
问题描述:
在mapper中的selected中希望执行时间的过滤,代码如下
"<when test='startDate!=null'>",
" and foal_date >= '#{startDate}' ",
"</when>",
"<when test='endDate!=null'>",
" and foal_date <= '#{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 > '${startDate}' ",//注意看,此处是$,问题的原因就是加了‘’之后导致运行时把tnd的#认为是一个注释了!
"</when>",
"<when test='endDate != null'>",
" and create_time < '${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 等务必使用${}