Blankman
Blankman

Reputation: 266988

Suggestions for building sql strings with jdbctemplate

I currently have this:

MyObject myObject = getJdbcTemplate().queryForObject("select * from my_objects where id = ?",
                new Object[]{new Integer(id)},
                new MyObjectRowMapper());

Now in my method I want to pass an enumeration:

SortOrder.ASC
SortOrder.DESC

So it will either be:

ORDER BY ID ASC

or

ORDER BY ID DESC

So inside the sql string, do I just add another '?' or do I have to build up the string like:

"select * from abc ORDER BY ID " + sortOrder;

Is there a preferred way?

Upvotes: 1

Views: 700

Answers (2)

JB Nizet
JB Nizet

Reputation: 691705

You have to use the second way. A prepared statement isn't just a "query-replace placeholders by the String I pass". All parameters must be typed values to insert into the syntax tree generated from the query. You can't pass a portion of a query as a parameter.

Upvotes: 2

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

You can not change the query in PreparedStatements so you can not use ? for asc or desc. I think concatenation is the simplest way you can use.

Upvotes: 0

Related Questions