String xx=" select * from( select CLASSES,ID,TITLE ,to_char(pub_date,'yyyy-mm-dd')pub_date,URL,rownum rn from urlmaptab where classes=? and flag='1' and auth_flag in('G') "+ " and rownum<=? ) where rn>=? order by ? desc";
list=getJdbcTemplate().queryForList(xx,new Object[]{classes,end,begin,order});
使用spring jdbcTemplate带预编译的查询方法查询时,发现结果是乱序的,也就是说oder by 失效了,问题出在哪里呢?
上网查阅资料:得到如下
The specification isn't explicit, but the context of the section on
PreparedStatements makes it clear that the ? placeholders are to be used
to set data, i.e. SQL literals, and not to allow you to vary database
schema objects like tables, columns, etc. This is natural and
understandable; the amount of pre-compilation a driver could do would be
extremely limited if the ? could stand for tables or columns.
In the example of the OP, the driver (either at the JDBC or database
level) will compile the prepared statement differently depending on
whether there is an index on the order by column. Allowing the order by
column to vary defeats this and dilutes the effectiveness of the
PreparedStatement.
Placeholders ? can only be used for parameter values but not with column and sort order directions.
大概意思都是说占位符?,不能是数据库表中的表名,字段等database
schema objects。
采用拼接sql字符串的方式,查询结果正常:
String xx=" select * from( select CLASSES,ID,TITLE ,to_char(pub_date,'yyyy-mm-dd')pub_date,URL,rownum rn from urlmaptab where classes=? and flag='1' and auth_flag in('G') "+" and rownum<=? ) where rn>=? order by "+sort+" "+order;