Using a PreparedStatement with a SELECT statement and LIKE clause

By Alvin J. Alexander, devdaily.com

Here's a quick example of how to use a JDBC PreparedStatement with an SQL SELECT query when accessing a database. To make it a little more complicated I added a LIKE clause to the SELECT statement. So, this is really an example of a PreparedStatement that uses a SELECT query that uses a LIKE clause.

For me, the hard part of this example is figuring out how to use wildcard characters with your PreparedStatement parameter. I tried adding it directly to the SQL SELECT statement, then realized I just needed to use the ? character there, and then add the wildcards in the ps.setString() statement.

Here's a sample Java method that shows this PreparedStatement/SELECT/LIKE combination:

private List getTopics (Connection conn, String searchCriteria)
throws SQLException
{
  List blogs = new LinkedList();
  String query = "SELECT id, text FROM blogs WHERE UPPER(text) LIKE ?";
  try
  {
    // going to do a search using "upper"
    searchCriteria = searchCriteria.toUpperCase();

    // create the prepared statement and add the criteria
    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1, "%" + searchCriteria + "%");

    // process the results
    ResultSet rs = ps.executeQuery();
    while ( rs.next() )
    {
      Blog blog = new Blog();
      blog.setID  ( rs.getInt("id") );
      blog.setText( rs.getString("text") );
      blogs.add(blog);
    }
    rs.close();
    ps.close();
  }
  catch (SQLException se)
  {
    // log exception;
    throw se;
  }
  return blogs;
}  

As you can see, the setup work is a lot like using a PreparedStatement with an INSERT, UPDATE, or DELETE, but in the case of a SELECT statement you process the results you get back from the ResultSet. As mentioned, the trick is making sure your String just says LIKE ?, and then adding the wildcard characters you need (i.e., the % character) to your PreparedStatement parameter.


devdaily logo