Search code examples
sqlitesearchsql-like

Android SQLite Like query


The following Query works Fine in my app

db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,KEY_FAULTREF,KEY_WORKNUM,KEY_ORIGNUM,KEY_REPBY,KEY_REPDATTIM,KEY_DESCRIPTION}, KEY_FAULTREF + "='" + strname+ "'", null,null, null, null, null);

strname is what I am searching for but it will only bring back records that EXACTLY match this

I want to modify so it brings back everything that CONTAINS strname (eg something like strname)

I tried the following but my app crashed

db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,KEY_FAULTREF,KEY_WORKNUM,KEY_ORIGNUM,KEY_REPBY,KEY_REPDATTIM,KEY_DESCRIPTION}, KEY_REPBY + "LIKE %'" + strname+ "'%", null,null, null, null, null);

I know its the LIKE statement but any ides where im going wrong?

Your help appreciated

Mark


Solution

  • The % wildcards must be part of the string:

    ... + " LIKE '%" + strname+ "%'", ...
    

    Please note that this code will blow up when the string contains a quote. You should use parameters instead:

    db.query(true, DATABASE_TABLE,
             new String[] {KEY_ROWID,KEY_FAULTREF,KEY_WORKNUM,KEY_ORIGNUM,KEY_REPBY,KEY_REPDATTIM,KEY_DESCRIPTION},
             KEY_REPBY + " LIKE ?",
             new String[] { "%" + strname + "%" },
             null, null, null, null);