how to use glob with sqlite in android

雨燕双飞 提交于 2019-12-24 08:39:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!