星期二, 2月 21, 2012

[Java] PreparedStatement Order by 失效問題!!

使用PreparedStatement操作Order by指令無法得到排序的解法!!
參考Stackoverflow:PreparedStatement not returning ordered ResultSet 至一文。

範例:
透過PreparedStatement來執行以下sql子句



SELECT name, id, xyz FROM table ORDER BY ?
ps.setString(1, "xyz");

失敗的原因為

The database will see the query asSELECT name, id, xyz FROM table ORDER BY 'xyz'
That is to say, order by a constant expression (the string 'xyz' in this case). Any order will satisfy that

解決的方法如下
指定排序的欄位為第三個select欄位索引3(即為xyz)
ps.setInteger(1, 3);

如果要加上排序的話目前我暫時將它寫入Sql中,再自行透過變數切換排序方式 Orz
SELECT name, id, xyz FROM table ORDER BY ? ASC

SELECT name, id, xyz FROM table ORDER BY ? DESC

沒有留言:

張貼留言

留個話吧:)