【问题标题】:Search sqlite android搜索sqlite android
【发布时间】:2015-11-09 21:47:35
【问题描述】:

对不起我的英语。我尝试动态创建搜索。示例:我们输入搜索词hellow,我输入h-> 他是搜索所有以后者开头的词he-> 他是搜索所有以后者开头的词hel-> 他是搜索... 等等。单词可能是大写和小写,例如HeLLow。我的例子

   public List<Map<String, String>> getSearch(String tableName, String search) {
        String query = "SELECT * FROM " + tableName + " WHERE `name` LIKE " + search;

        Cursor cursor = db.rawQuery(query, null);
        List<Map<String, String>> list = new ArrayList<>();
        String[] names = cursor.getColumnNames();

        if(cursor.moveToFirst()) {
            do{
                Map<String, String> map = new HashMap<String, String>();
                for (int i = 0; i < names.length; i++) {
                    map.put(names[i], cursor.getString(i));
                }
                list.add(map);

            } while (cursor.moveToNext());
        }

        return list;
    }

我尝试这样做:

String query = "SELECT * FROM " + tableName + " WHERE name = " + search;

String query = "SELECT * FROM " + tableName + " WHERE name MATCH " + search;

也不行,我一直都是list = 0

【问题讨论】:

  • 所以这个和android或者sqlite无关,但是可以改写成how does LIKE works in SQL

标签: android sqlite search


【解决方案1】:

当您逐字母构建单词时,将其附加通配符符号,即%,例如“he%”,下一个字母“hel%”

构建search 变量,对于添加或删除的字母的每次迭代,每次都附加通配符,例如'Hel%',然后像这样组合SQL

String query = "SELECT * FROM " + tableName + " WHERE name LIKE " + search;

关键字是 SQL 词 LIKE,它将让您找到包含诸如 Hel% 之类的词的行。

【讨论】:

  • 感谢您的回答,如果我输入 ow 它找到我的话(hellow)?
  • 我像这样创建String query = "SELECT * FROM " + tableName + " WHERE name LIKE " + "'"+ search +"%'"; 它的工作很好。但是,如果我有这样的词 hellow-world 并且我输入 world 它找不到我的词(
【解决方案2】:

或者,考虑为 SQLite 使用 FTS(全文搜索)扩展。使用 FTS 进行查询的速度非常快,提供不分大小写的结果,并且原生附带 SQLite for Android SDK。

您可以在下面找到一个工作示例: https://github.com/dawidgdanski/Bakery

希望这能有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多