通过条目的第一个字母查询sqlite数据库

时间:2013-02-05 10:35:26

标签: android regex sqlite

我创建了一个TabLayout,我想通过所选标签显示我的数据库条目。以下是包含查询的代码段:

public Cursor filteredItems(int tabPosition) throws SQLException {
        Log.d(TAG, "filteredItems called, Parameter: "+tabPosition); 

        String filter = ""; 
        if(tabPosition == 0){
            filter = "[a-cA-C]%";
        }else if(tabPosition == 1){
            filter = "[d-fD-F]%";
        }else{
            Log.d(TAG, "default tab"); 
            filter = "[a-zA-Z]%";
        }

        Cursor cursor = null;
        try{
            open();
            String query ="SELECT _id, surname, prename, street, zipcode, telephone, email FROM "+Database.getMyDbTable()+" " +
                    "WHERE surname LIKE '"+filter+"';";
            Log.d(TAG,"Query "+query);
            cursor = database.rawQuery(query, null);
        }catch(Exception ex){
            Log.e(TAG, "Could not get list");
            CharSequence text = dataNotFound;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

        return cursor;
    }

不幸的是,过滤器不起作用 - 查询的结果总是为空(表不是空的 - 我已经检查过了)。

4 个答案:

答案 0 :(得分:1)

您需要为此目的使用通配符。阅读http://sqlite.awardspace.info/syntax/sqlitepg03.htm

尝试

SELECT _id, surname, prename, street, zipcode, telephone, email FROM table WHERE surname LIKE '<your letter(s)>%'

答案 1 :(得分:1)

首先,LIKE运算符不采用正则表达式。不幸的是,在Android中不支持执行此操作的REGEXP运算符。

解决方案:使用LIKE和逻辑OR。

String query ="SELECT _id, surname, prename, street, zipcode, telephone, email FROM "+Database.getMyDbTable()+" WHERE surname LIKE 'a%' OR surname LIKE 'b%' OR surname LIKE 'c%';";

答案 2 :(得分:0)

尝试类似:

"SELECT _id, surname, prename, street, zipcode, telephone, email FROM " + Database.getMyDbTable() + " WHERE substr(" + Database.getMyDbTable()  +",1) LIKE " + <yourletter>

使用substr,您只比较第一个字母。

答案 3 :(得分:0)

LIKE无法与字符集匹配。

由于您只关心第一个字母,因此您可以使用BETWEEN代替:

SELECT ... FROM MyTable WHERE surname BETWEEN 'A' AND 'Czzzz'

要处理大写和小写,请使用两个条件,或更改排序规则:

SELECT ... FROM MyTable WHERE surname BETWEEN 'A' AND 'Czzzz'
                           OR surname BETWEEN 'a' AND 'czzzz'

SELECT ... FROM MyTable WHERE surname COLLATION UNICODE BETWEEN 'A' AND 'Czzzz'

只有在使用相同的排序规则声明列或索引时,后者才能使用索引。