Prepared Statment - Order by

Language : Java

Database : Oracle

I am trying to use the following sql

select * from EMPLOYEE WHERE EMPLOYEE_LASTNAME='ABC'

ORDER BY EMPLOYEE_LASTNAME

using prepared statment :

select * from EMPLOYEE WHERE EMPLOYEE_LASTNAME=?

ORDER BY ?

I set the parameters using

pstmt.setString(1,'ABC');

pstmt.setString(2,'EMPLOYEE_LASTNAME'); (instead of this I could also use

pstmt.setInt(2,1) -- but this also does not sort the results)

After I execute the prepared statment I get the correct results but they are not Sorted i.e the ORDER BY clause does not work ?

Has anyone come across this problem before ? Can anyone provide any solutions ?

Thanks in advance,

Ann.

[762 byte] By [ann460a] at [2007-10-1 0:08:09]
# 1
Obviously you should not use ? for the field name. ? is okay for the field value.
BIJ001a at 2007-7-7 15:52:18 > top of Java-index,Administration Tools,Sun Connection...
# 2
In the Order by clause you have to mention Field Name .Question here is why ORDER BY ? does not work it does not give an exception - query executes fine it the results are not sorted.Thanks,Ann.
ann460a at 2007-7-7 15:52:18 > top of Java-index,Administration Tools,Sun Connection...
# 3

I also have the same problem. But i do not why it can not be used? I guess when it is replacing the '?' with the proper value in the query then it should even sort. Logically speaking it should work. But there is one more thing possible that the 'order by' part of the query might not have been saved in the cache. This is my guess. I dont know beyond that how it can be resolved. I need to do some research too. Any response would be appreciated.

Thanks in advance.

DevCool !

devpoola at 2007-7-7 15:52:18 > top of Java-index,Administration Tools,Sun Connection...
# 4

Another way to solve this problem is to "not" use prepared statment for order by as below

query = "select * from EMPLOYEE WHERE EMPLOYEE_LASTNAME=? ";

if (orderBtStr.equals("EMPID")) {

query = query + "ORDER BY EMPLOYEE_ID";

} else {

query = query + "ORDER BY EMPLOYEE_LASTNAME";

}

pstmt = con.prepareStatement(query);

pstmt.setString(1,lastName);

rs = pstmt.executeQuery();

ann460a at 2007-7-7 15:52:18 > top of Java-index,Administration Tools,Sun Connection...