Parameter index out of range (1 > number of parameters, which is 0
原创 2018-01-09 15:20 阅读(1475)次
用hibernate操作数据库时,写了一个模糊查询,用参数形式传入SQL,语句如下:
select * from article where 1=1 and title like '%?%' order by create_time desc
调用时传入参数时一直报错:Parameter index out of range (1 > number of parameters, which is 0,如图:
我调试了下代码,参数都是没错的,语句中的问号也是没错的,后来百度了下,原来?问不能用引号''包着,否则会当成正式参数传入sql语句中,不会当成占位符。于是我把引号去掉,改成:and title like %?%,传入参数'java'又报错了,hibernate把?解析成参数时语句变成and title like %'java'%,错误如下:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%'java'% order by create_time desc' at line 1
通过上面就知道了hibernate解析参数后会自动加上''引号,要想实现模糊查询时,可以通过提前拼接好百分号%,语句改成如下:
select * from article where 1=1 and title like ? order by create_time desc
问号里的参数我们传入'%java%' 就可以了