cant use like clause in android app

后端 未结 7 775
萌比男神i
萌比男神i 2020-12-07 01:23

I am working on a database with sqllite in an android app I want to retrieve sm data using a like clause ex:

Cursor c = myDB.query(MY_DATABASE_TABLE, null,          


        
相关标签:
7条回答
  • 2020-12-07 01:44

    a simple way is to use the concatenate operator ||

    "SongName LIKE '%'||?||'%'"
    

    so there is no need to edit the match_str.

    Cursor c = myDB.query(MY_DATABASE_TABLE, null, " SongName LIKE '%'||?||'%'" , 
           new String[]{match_str}, null, null,"SongHit  DESC");
    

    from https://stackoverflow.com/a/46420813/908821

    0 讨论(0)
  • 2020-12-07 01:48

    If you wish to use query() instead of rawQuery(), you can do it like so:

    // searchString is the string to search for
    final String whereClause = "MyColumnName" + " like ?";
    String[] whereArgs = new String[]{"%" + searchString + "%"};
    
    Cursor cursor = sqLiteDatabase.query("MyTableName",
            null, // columns
            whereClause, // selection
            whereArgs, // selectionArgs
            null, // groupBy
            null, // having
            null, // orderBy
            null); // limit
    
    0 讨论(0)
  • 2020-12-07 01:49

    hi Are you getting any exception while executing the above query. Try by removing the "=" symbol infront of the question mark in the like condition. Else try using

    db.rawQuery(sql, selectionArgs)
    
    0 讨论(0)
  • 2020-12-07 01:50

    This works perfectly for me...

    "Songname LIKE ? "...
    
    cursor = database.rawQuery(query, new String[]{"%" + searchTerm + "%"});
    
    0 讨论(0)
  • 2020-12-07 01:52

    Try this:

    String[] args = new String[1];
    args[0] = "%"+song+"%";
    Cursor friendLike = db.rawQuery("SELECT * FROM songs WHERE SongName like ?", args);
    
    0 讨论(0)
  • 2020-12-07 02:01

    This:

    " SongName LIKE '%"+"=?"+"%'"
    

    Will end up looking like this when the SQL interpreter sees it:

    " SongName LIKE '%=?%'"
    

    And that will match any SongName that contains a literal "=?" and I don't think that's anything like what you want.

    A % matches any sequence of characters in an SQL LIKE, it is essentially the same as .* in a regular expression; so, if you want to match at the beginning then you don't want a leading %. Also, your ? placeholder needs to be outside the single quotes or it will be interpreted as a literal question mark rather than a placeholder.

    You want something more like this:

    String[] a = new String[1];
    a[0]       = match_str + '%';
    Cursor   c = myDB.rawQuery("SELECT * FROM songs WHERE SongName LIKE ?", a);
    

    If you wanted to be really strict you'd also have to escape % and _ symbols inside match_str as well but that's left as an exercise for the reader.

    0 讨论(0)
提交回复
热议问题