LIKE clause with PreparedStatement

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.

Did you like this? If so, please
tell a friend
about it, and subscribe to the blog RSS feed.

Share/Save/Bookmark

If you enjoyed this post, make sure you subscribe to my RSS feed!



Related Posts:
  • Recursively delete a directory
  • Sending an e-mail using WebSphere Mail session settings.
  • Sorting an ArrayList of objects.
  • Exception stackTrace to a String Variable
  • Defensive coping


  • One Response to “LIKE clause with PreparedStatement”  

    1. 1 An

      You are brilliant. I got the same problem, and your solution helps me to solve it.
      Thanks so much
      An

    Leave a Reply