问题
I have a database of 23,000 words. I want to have the query return all words that start with a certain search string. After reading sqlite LIKE problem in android I was able to get a working query using LIKE. Here it is:
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = { KEY_WORD };
String sqlTables = TABLE_WORDS;
//String selection = KEY_FUZZYWORD + " =?"; // for an exact match
String selection = KEY_FUZZYWORD + " LIKE ?";
String[] selectionArgs = { searchString + "%" };
String limit = Integer.toString(WORD_QUERY_LIMIT);
qb.setTables(sqlTables);
Cursor cursor = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null, limit);
The key lines are
String selection = KEY_FUZZYWORD + " LIKE ?";
String[] selectionArgs = { searchString + "%" };
But I also read Why do we need the GLOB clause in SQLite? Case sensitivity is fine for my situation so I thought I would try it. How do you set this up using SQLiteQueryBuilder with selectionArgs? I was having a lot of trouble finding an example. (I don't want to use a rawQuery in order to avoid SQL injection.)
回答1:
It is very similar to what you have already.
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = { KEY_WORD };
String sqlTables = TABLE_WORDS;
String selection = KEY_FUZZYWORD + " GLOB ?";
String[] selectionArgs = { searchString + "*" };
String limit = Integer.toString(WORD_QUERY_LIMIT);
qb.setTables(sqlTables);
Cursor cursor = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null, limit);
the key lines being
String selection = KEY_FUZZYWORD + " GLOB ?";
String[] selectionArgs = { searchString + "*" };
Further reading:
- SQLite - GLOB Clause
- SQL As Understood By SQLite (scroll down to "The LIKE and GLOB operators")
来源:https://stackoverflow.com/questions/29773891/how-to-use-glob-with-sqlite-in-android