% sign in Java’s PreparedStatement

PreparedStatement ps = con.createStatement("select * from table1 where last_name like ?");
ps.setString(1, "'%"+lastName+"'");

Will this work the same as…

Statement s = con.createStatement("select * from table1 where last_name like %"+ lastName);

Or does PreparedStatement strip out the % sign?

Answer

% is a wildcard character (in Oracle at least), so in theory both should work the same (assuming you add the missing single-quotes)

However, the first would be regarded as better practice, since it may enable the database optimser not to re-parse the statement. The first should also protect you against SQL injection whereas the second may not.

Leave a Reply

Your email address will not be published. Required fields are marked *