Java Program not locating all keywords while using LIKE SQL statement



I’m building an application, and I’m trying to use PreparedStatements in order to execute SQL queries. Basically, there is a search option and I’m trying to use SQL LIKE method in the search box. The name is taken from the search box and is inserted into the PreparedStatement.

try {

    PreparedStatement ps2 = con.prepareStatement("SELECT * FROM books WHERE book_name LIKE ? AND status=?");
    ps2.setString(1, name2 + "%");
    ps2.setString(2, stat);
    ResultSet rs = ps2.executeQuery();

    dt.setRowCount(0);
    while (rs.next()) {
        Object ob[] = {
            rs.getString("book_name"),
            rs.getString("book_author")
        };
        dt.addRow(ob);
    }

} catch (Exception af) {
    jLabel29.setText("No result Found !");

}
break;

Where name2 is the what the user searches. However, when I do this, the program is only giving an output if the first word in the column “book_name” matches the searched item. For example, for a sentence “My name is Jack”, if I type in “Jack” or “name”, there is no output, but if I type in “My”, the whole row is detected.

Answer

It should be LIKE '%<searchString>%' to consider all the preceeding and succeeding characters for wildcard search.

In other words, use:

ps2.setString(1, "%" + name2 + "%"); 


Source: stackoverflow