我需要删除键包含特定字符串的数据库条目。
转义前的SearchString:
EntityCollection(Id='INST_PAT_ID%200100010050057716')
转义代码:
logger.debug("wildCard: " + wildCard);
String escapedString = wildCard.replace("%", "\\%");
String escapedString2 = escapedString.replace("'", "\\'");
String escapedString3 = escapedString2.replace("_", "\\_");
logger.debug("escapedString3: " + escapedString3);
转义后的SearchString:
EntityCollection(Id=\''INST\_PAT\_ID\%200100010050057716\'')%'' {escape '\'}' in key.
SQL 语句如下所示。
final String where = "key LIKE ?";
final String[] args = new String[] { DatabaseUtils.sqlEscapeString("'%" + escapedString3 + "%'" + " {escape '\\'}") };
int success = database.delete(CacheDatabaseHelper.DATABASE_TABLE, where, args);
logger.debug("Delete attempt affected " + success + " lines!");
logger.debug("Deleted all cache entries from database containing: " + args[0] + " in key.");
但是我无法让它工作,因为它生成了错误的 SQL 语句。
最佳答案
由于您在查询中使用 ?
,因此它已参数化。您没有使用连接(看起来),因此您无需担心转义字符。只需使用原始字符串即可。但是,由于 where
中没有 %
字符,因此您的查询相当于使用 =
。
关于java - SQLite LIKE 语句和转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12087146/