Mahdi_Nine
Mahdi_Nine

Reputation: 14751

problem with prepare statement

preparedStatement = connection.prepareStatement("select fname,lname, "
                    + "sportman_code,start,finish,salary,amount,number,pnumber "
                    + "from sportman,customer "
                    + "where customer.customer_code = "
                    + "sportman.customer_code order by ? limit ?,?");



            preparedStatement.setString(1, "fname");
            preparedStatement.setInt(2, 0);
            preparedStatement.setInt(3, 9);
            resultSet = preparedStatement.executeQuery();

order by didn't work. why?

when i put fname instead ? it work correctly.

"sportman.customer_code order by fname limit ?,?");

how can i do that?

Upvotes: 0

Views: 525

Answers (3)

Isaac Truett
Isaac Truett

Reputation: 8884

Binding works for literals in the query, not for keywords or identifiers. You'll need to use another approach for sanitizing the sort field if you want it to be dynamic.

Upvotes: 0

Erik
Erik

Reputation: 4105

Your ORDER BY works, but not as you expect it to. When you use

 preparedStatement.setString(1, "fname");

it will make an ORDER BY like this

 ORDER BY 'fname'

and not as you expect

 ORDER BY fname

The code in your question will then be like sorting a package of M&Ms alphabetically

Upvotes: 2

James C
James C

Reputation: 14149

You can't bind in identifiers like table names or column names, only values that you want to insert, compare, etc

Upvotes: 1

Related Questions