0

Hey I have problem with preparedStatement, I want to find min for few columns, I'm iterating over the names of columns and inserting them inside my preparedStatement like that

connection.prepareStatement("SELECT min( ? ) as min FROM test");
minStatement.setString(1, "some_column");

and when retrieving from ResultSet I'm getting the column name, in this case the result is "some_column" and should be 0. When using normal statement it does return right value. I have no idea what I'm doing wrong. Thanks for any help.

1
  • The idea behind a prepared statement is that the DB only compiles and optimizes the query once. It can't do this if the location is going to be changing every time the query is used Commented Nov 14, 2013 at 23:49

1 Answer 1

4

You cannot specify a column name in prepared statement like this, what you get is:

SELECT MIN('some_column') AS min FROM test

Instead of:

SELECT MIN(some_column) AS min FROM test

So, your query selects the minimal value 'some_column'... which is 'some_column'.

You could, instead, try that:

connection.prepareStatement("SELECT min(" + some_column + " ) as min FROM test");

But this may lead to injection attacks.

Sign up to request clarification or add additional context in comments.

1 Comment

I was close with my thinking, thank you for answer, in my case injections are not the problem:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.