views:

700

answers:

1

Here's my current SQL statement:

SEARCH_ALBUMS_SQL = "SELECT * FROM albums WHERE title LIKE ? OR artist LIKE ?;";

It's returning exact matches to the album or artist names, but not anything else. I can't use a '%' in the statement or I get errors.

How do I add wildcards to a prepared statement?

(I'm using Java5 and MySQL)

Thanks!

+6  A: 

You put the % in the bound variable. So you do

   stmt.setString(1, "%" + title + "%");
   stmt.setString(2, "%" + artist + "%");
Paul Tomblin
So, what if the bound variable actually had a '%' character in it?
Eric Noob
@Eric - Then you don't need to add it. There's nothing magical about doing it in the setString rather than anywhere else.
Paul Tomblin
If your bound variable has a literal '%' you should escape it as '\%'. See Java method java.lang.String.replace().
Bill Karwin