Parameter index out of range (2 > number of parameters, which is 1)


今天在實現一個功能時遇到一個問題,解決了很久。結果是#{}與${}使用錯誤的原因。但是具體原因還不是很清楚,寫此篇總結,知道的可以交流。

具體描述為:通過教師的頭銜(1高級講師2首席講師)及名稱進行模糊查詢,報如下錯誤:

org.springframework.dao.TransientDataAccessResourceException:

### Error querying database.  Cause: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).

### The error may exist in file [E:\javaEE+android\mooc\workspace\edu-mooc\target\classes\mybatis\mappers\admin\teacher\TeacherMapper.xml]

### The error may involve com.edu.mooc.admin.mapper.TeacherMapper.quearyTeacherListBySolr-Inline

### The error occurred while setting parameters

### SQL: SELECT count(*) FROM EDU_TEACHER WHERE EDU_TEACHER.`STATUS` = 0 AND EDU_TEACHER.IS_STAR = ? AND EDU_TEACHER.`NAME` LIKE '%?%'

### Cause: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).

; SQL []; Parameter index out of range (2 > number of parameters, which is 1).; nested exception is java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).

 

參看一些網上解釋:就是當設置參數時,沒有相應的問號與之匹配(或者根本就沒有?號).

分析錯誤:

Parameter index out of range (2 > number of parameters, which is 1).

翻譯為:找到了1個問號,卻插入了2個值,導致參數越界(根據得到的信息打印將很容易判斷數據是否與數據庫字段匹配等小問題)。

 

看看sql代碼:

SELECT

      <include refid="edu_teacher_columns"/>

      FROM EDU_TEACHER

      <where>

         EDU_TEACHER.`STATUS` = 0

         <if test="isStar > 0">

            AND EDU_TEACHER.IS_STAR = #{isStar}

         </if>

         <if test="keyWords != null and keyWords != '' ">

            AND EDU_TEACHER.`NAME` LIKE '%#{keyWords}%'

         </if>

         ORDER BY SORT DESC,CREATE_TIME ASC

      </where>

將'%#{keyWords}%'修改為'%${keyWords}%'后結果正確

 

日志信息輸出結果為:

==>  Preparing: SELECT count(*) FROM EDU_TEACHER WHERE EDU_TEACHER.`STATUS` = 0 AND EDU_TEACHER.IS_STAR = ? AND EDU_TEACHER.`NAME` LIKE '%李%'

==> Parameters: 1(Integer)

<==    Columns: count(*)

<==        Row: 3

<==      Total: 1

==>  Preparing: SELECT EDU_TEACHER.ID, EDU_TEACHER.NAME, EDU_TEACHER.EDUCATION, EDU_TEACHER.CAREER, EDU_TEACHER.IS_STAR, EDU_TEACHER.PIC_PATH, EDU_TEACHER.STATUS, EDU_TEACHER.CREATE_TIME, EDU_TEACHER.UPDATE_TIME, EDU_TEACHER.SUBJECT_ID, EDU_TEACHER.SORT FROM EDU_TEACHER WHERE EDU_TEACHER.`STATUS` = 0 AND EDU_TEACHER.IS_STAR = ? AND EDU_TEACHER.`NAME` LIKE '%李%' ORDER BY SORT DESC,CREATE_TIME ASC limit ?,?

==> Parameters: 1(Integer), 0(Integer), 10(Integer)

<==    Columns: ID, NAME, EDUCATION, CAREER, IS_STAR, PIC_PATH, STATUS, CREATE_TIME, UPDATE_TIME, SUBJECT_ID, SORT


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM