Jan
18
LIKE clause with PreparedStatement
Posted by | Posted in Java | Posted on 18-01-2008
Tagged Under : Java, JDBC
How to use a LIKE clause with PreparedStatement object? I had this requirement and all the methods that I tried were not working. Java was not giving me any compile time nor run time errors. However the result was not coming as expected. I did some search on that and finally I got the solution. When we use PreparedStatement with LIKE clause, give the percentage sign in your setXXX method.
For eg:
String firstName ="A"; String query = "SELECT NAME, EMAIL FROM USER WHERE USERID LIKE ?"; PreparedStatement stmt = con.prepareStatement(query); stmt.setString(1, "%"+firstName+"%"); ResultSet rst = stmt.executeQuery(); |
The above code is tested in WebSpere Application Server + Oracle and Tomcat + MySQL environments and is working fine.


