如何在 android 中将 glob 与 sqlite 一起使用

how to use glob with sqlite in android

我有一个包含 23,000 个单词的数据库。我想要查询 return 所有以特定搜索字符串开头的单词。阅读 sqlite LIKE problem in android 后,我能够使用 LIKE 获得有效的查询。这是:

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);

重点是

String selection = KEY_FUZZYWORD + " LIKE ?";
String[] selectionArgs = { searchString + "%" };

但我还阅读了 Why do we need the GLOB clause in SQLite? 区分大小写适合我的情况,所以我想我会尝试一下。如何使用带有 selectionArgs 的 SQLiteQueryBuilder 进行设置?我很难找到一个例子。 (我不想使用 rawQuery 来避免 SQL 注入。)

它与您已有的非常相似。

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);

关键行是

String selection = KEY_FUZZYWORD + " GLOB ?";
String[] selectionArgs = { searchString + "*" };

进一步阅读: