sqljdbc

How do you escape special characters in SQL Where clause?


How do you escape special characters in SQL Where clause? The SLASH (/) specifically. I can make it work with "LIKE" but I need the SQL to match the exact URL since "/path/to/file/" returns both rows:

URLs in database:

"/path/to/file/"
"/path/to/file/*/"

StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM MY_TABLE");
sb.append("WHERE URL LIKE '%" + url + "%'");

return getNamedParameterJdbcTemplate().query(sb.toString(), new MyTableMapper());

Solution

  • In SQL the slash doesn't need to be escaped. You can use slashes in the query without problems.

    StringBuilder sb = new StringBuilder();
    sb.append("SELECT * FROM MY_TABLE");
    sb.append("WHERE URL = '" + url + "'");
    

    This query will work perfectly if the url variable is something like /path/to/file/.