Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

sqlite - cant use like clause in android app

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, " SongName LIKE '%"+"=?"+"%'" , 
           new String[]{match_str}, null, null,"SongHit  DESC");

It should give all SongName starting with match_str but its not working.Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...