0

I have the query like : select domain,hits from temp order by domain desc limit 10 offset 0; now running through JDBC and prepared statement my query converted to:

String prepareselectSQL="select domain,hits from temp order by ? ? limit ? offset ?;";

 PreparedStatement preparedStatement = null;
preparedStatement = connection.prepareStatement(prepareselectSQL);
preparedStatement.setString(1, "domain");
preparedStatement.setString(2, "desc");
preparedStatement.setInt(3, 10);
preparedStatement.setInt(4, 0);

ResultSet rs = preparedStatement.executeQuery();

now above code gives me an error :

org.postgresql.util.PSQLException: ERROR: syntax error at or near "$2"

please help on this,how will i use consecutive question mark in preparestatement.

Asha Koshti
  • 2,763
  • 4
  • 22
  • 30
  • 1
    You can't use positional parameters in the `ORDER BY` clause. Your options include appending your own `ORDER BY` clause, which might expose to you injection attacks, or to just use separate statements for different `ORDER BY` clauses. – Tim Biegeleisen May 03 '18 at 11:39
  • @TimBiegeleisen My application is such where sorting is dynamic based on user selection and also the type of the sorting .so i need to use parameter on both the side to save from injection.the code given is example where 1st and 2nd both parameter will be dynamic based on request. – Asha Koshti May 03 '18 at 11:43
  • Not a problem. Just duplicate each statement to handle ascending/descending sorting order. Or, you could try to append an `ORDER BY` clause, with the caveats I gave above. – Tim Biegeleisen May 03 '18 at 11:44

0 Answers0