積少成多 ---- 僅以此致敬和我一樣在慢慢前進的人兒
問題: 在sqlserver 進行模糊查詢,出現問題
最初使用“concat”,進行拼串操作,如下所示:
<select id = "queryCount" resultType="int" > select count(*) from t_user <where> <if test = "queryText!= null"> loginacct like concat("%", #{queryText}, "%) </if> </where> </select>
運行結果:“concat” 是不是可以識別的函數,不是內置函數
查詢結果: “concat”方法進行拼串,只適用於mysql 和 oracle, 不適用於sqlserver,這個函數是用來連接字符串, sqlserver中沒有,可以使用 + 連接符號搞定
解決方案:使用傳統的拼串操作,“like”操作嘗試:
嘗試一: 使用占位符(#{})
<select id = "queryCount" resultType="int" > select count(*) from t_user <where> <if test = "queryText!= null"> loginacct like '%#{queryText}%' </if> </where> </select>
運行結果:
Preparing: select count(*) from t_user WHERE loginacct like '%?%'
com.microsoft.sqlserver.jdbc.SQLServerException: 索引 1 超出范圍。
查詢結果:在使用占位符進行模糊查詢時不能把問號放在引號里面,問號的位置必須跟字段名同級;(不理解)
解決方案:like '%' + #{quertText} + '%’(成功運行)
<select id = "queryCount" resultType="int" >
select count(*)
from t_user
<where>
<if test = "queryText!= null"> loginacct like '%' + #{queryText}+ '%' </if>
</where>
</select>
嘗試二: 使用EL表達式(成功運行) <select id = "queryCount" resultType="int" > select count(*) from t_user <where> <if test = "queryText!= null"> loginacct like '%${queryText}%' </if> </where> </select>
存在問題:使用 ${}無法防止sql注入
結論:sqlserver 模糊查詢中, 優先使用 like '%' + #{quertText} + '%’進行操作
sqlserver 分頁模糊查詢例碼:(供自己忘記后查看)
<select id = "queryList" resultType="T_user"> select top ${pagesize}* from t_user <where> <if test = "queryText!=null">loginacct like '%' + #{queryText}+ '%' and id not in (select top ${startIndex} id from t_user order by id) order by id </if> </where> <where> <if test = "queryText==null"> id not in (select top ${startIndex} id from t_user order by id) order by id </if> </where> </select>
注意事項: 單個或者是多個條件查詢,都是只有一個“where” 條件之間使用 “and” 連接
2020 / 03 / 12
今天做模糊查詢的時候, 回來看發現使用上面的不行,折騰了半天, 雙引號換成單引號就可以,好奇怪
<select id = "productFuzzyQuery" parameterType="String" resultType="com.wchat.secondhand.entity.Items"> select id, address, goods, description, price, location from t_item where goods like '%' + #{product} + '%' </select>
很奇怪,上面原來是可以的,今天測卻又是不行,哎
2020 -3-19
今天使用分頁,依據上面的寫法, 但是報錯顯示
ibatis Cause: com.microsoft.sqlserver.jdbc.SQLServerException: '@P0' 附近有語法錯誤
查詢資料:
https://blog.csdn.net/niqikun/article/details/49047153
http://yayihouse.com/yayishuwu/chapter/1765
又是一件很奇怪的事情