rtheunissen
rtheunissen

Reputation: 7435

Is it possible to use prepared statement placeholders for LIKE?

This fails:
db.prepareStatement("SELECT * FROM " + table + " WHERE " + column + " LIKE '?%'");

Because the ? is not recognized as a placeholder for a value. How should I work around this?

Upvotes: 2

Views: 564

Answers (3)

Bohemian
Bohemian

Reputation: 424983

Pass your value into the CONCAT() function:

db.prepareStatement("SELECT * FROM " + table 
    + " WHERE " + column 
  + " LIKE CONCAT(?, '%')");

The advantage of doing it this way is the code making the call doesn't need to know that the parameter is being used with a LIKE, so you could use the same parameter value with other non-LIKE queries.

Upvotes: 1

femtoRgon
femtoRgon

Reputation: 33341

Put the wildcard in the variable, rather than in the statement, like:

stmt = db.prepareStatement("SELECT * FROM " + table + " WHERE " + column + " LIKE ?");
stmt.setString(1, "myterm%");

Upvotes: 7

duffymo
duffymo

Reputation: 308733

Try including the percent sign as part of the LIKE parameter:

db.prepareStatement("SELECT * FROM " + table + " WHERE " + column + " LIKE ?"); 

I don't like the query much. I don't think you're saving much by concatenating table and column in this way.

Upvotes: 0

Related Questions