如何在 SQLite 中搜索相似的字符串 [英] how to search similar strings in SQLite

查看:54
本文介绍了如何在 SQLite 中搜索相似的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在表TABLE_TOURS"中搜索COLUMN_TITLE"中与query"相似的词,并返回一个列表List".请帮帮我

I want to search table "TABLE_TOURS" for similar words of "query" in cloumn "COLUMN_TITLE" and return a list "List". helps me plzz

public List<Tour> getWordMatches(String query, String[] columns) {
    String selection =  ToursDBOpenHelper.COLUMN_TITLE + " MATCH ?";
    String[] selectionArgs = new String[] {query+"*"};
    return query(selection, selectionArgs, columns);
}
public List<Tour> query(String selection, String[] selectionArgs, String[] columns) {
    Log.i(LOGTAG, "getwordsmatches result"+ selection +" "+ selectionArgs);
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(ToursDBOpenHelper.TABLE_TOURS);

    Cursor cursor = builder.query(dbhelper.getReadableDatabase(),
            columns, selection, selectionArgs, null, null, null);
    Log.i(LOGTAG, "cursor of db result "+ cursor);
    List<Tour> tours = cursorToList(cursor);
    Log.i(LOGTAG, "tours are "+ tours);
    if (cursor == null) {
        return null;
    } else if (!cursor.moveToFirst()) {
        cursor.close();
        return null;
    }
    return tours;
}

及其 cursorToList 方法:

and its cursorToList method:

private List<Tour> cursorToList(Cursor cursor) {
    List<Tour> tours = new ArrayList<Tour>();
    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            Tour tour = new Tour();
            tour.setId(cursor.getLong(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_ID)));
            tour.setTitle(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_TITLE)));
            tour.setCate(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_CATE)));
            tour.setDetail(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_DETAIL)));
            tour.setDescription(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_DESC)));
            tour.setImage(cursor.getString(cursor.getColumnIndex(ToursDBOpenHelper.COLUMN_IMAGE)));
            tours.add(tour);
        }
    }
    return tours;
}

推荐答案

您可以为此使用 SQL LIKE 语句.在 SQL 中,% 字符表示任意 0 个或多个字符的字符串.所以,例如,你可以写

You can use the SQL LIKE statement for this. In SQL, the % character represents any string of 0 or more characters. So, for example, you could write

SELECT * FROM MY_TABLE WHERE COLUMN_NAME LIKE '%dog%'

这将匹配任何包含狗"的字符串,例如狗"、狗"、我喜欢狗"和123dog321".

This will match any string containing "dog", such as "dog", "dogs", "I like dogs", and "123dog321".

您的确切参数会因表格的结构而异,但这是它的要点.

Your exact arguments will vary based on the structure of your table, but this is the gist of it.

这篇关于如何在 SQLite 中搜索相似的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆