使用mybatis查询时出现Parameter index out of range (1 > number of parameters, which is 0)的错误,网上总结主要为以下两个方面,而我的sql语句都没有涉及到。
1、模糊查询--like 的使用
Parameter index out of range (1 > number of parameters, which is 0).(参数索引超出范围)
在mybatis里面写就是应该是 like '%${name} %' 而不是 '%#{name} %'
2、设置参数时,没有相应的问号与之匹配
${name} 是不带单引号的,而#{name} 是带单引号的
所以,当你用到 like '%#{name}%' 会报这种错误
数据库错误:Parameter index out of range (1 > number of parameters, which is 0).
错误发生原因其实很简单,就是当设置参数时,没有相应的问号与之匹配(或者根本就没有?号).
与sql语句有关的原因如下:
1.?号被单引号包围。
(如setString(1,"slkdjfkd");时sql语句为:insert into table1 (c1,c2) values ('?','?'))。
此时?会被作为参数传入,而不会再传入 setString里面的值。
2.sql语句中没有?号,在后面用到了set语句。(如:select * from table);
此时无需传值。传值就会出错。
3.初学者很常见的错误:?---?
这两个问号是不同了,因为一个是中文,一个是英文,如果在sql语句中写入的是英文,将无法识别。
我的错误在于,sql中的字段名和查询条件中的字段名大小写不一致。
如:select plfbqzh,gcrqsj,qw,qy from table
<where>
<if test="dtBegin!=null and dtBegin !=''">
and GCRQSJ >= #{dtBegin}
</if>
<if test="dtEnd!=null and dtEnd !=''">
and GCRQSJ <= #{dtEnd}
</if>
and PLFBQZH in
<foreach item="item" index="listPlfbqzh" collection="listPlfbqzh" open="(" separator="," close=")">
#{item}
</foreach>
</where>
<if test="dtBegin!=null and dtBegin !=''">
and GCRQSJ >= #{dtBegin}
</if>
<if test="dtEnd!=null and dtEnd !=''">
and GCRQSJ <= #{dtEnd}
</if>
and PLFBQZH in
<foreach item="item" index="listPlfbqzh" collection="listPlfbqzh" open="(" separator="," close=")">
#{item}
</foreach>
</where>
此处sql语句只是举例,具体使用的sql语句在上一篇文章给出,是mybatis使用union、limit的联合查询,用于分页展示。