SQLite rawquery无法匹配预期的字符串

时间:2016-10-31 12:49:08

标签: android database sqlite wildcard

我正在使用此方法进行简单的数据库搜索。

public Cursor queryExpense(String createdDate, String createdTime, String category, String description, String amount) {
    SQLiteDatabase db = this.getReadableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_DATE + " LIKE ? AND " + COLUMN_TIME + " LIKE ? AND " +
            COLUMN_CATEGORY + " LIKE ? AND " + COLUMN_DESCRIPTION + " LIKE ? AND " + COLUMN_AMOUNT + " LIKE ? ";
    String mDate = createdDate.length() > 0 ? "%" + createdDate + "%" : "%";
    String mTime = createdTime.length() > 0 ? "%"  + createdTime + "%" : "%";
    String mCategory = category.length() > 0 ? "%" + category + "%" : "%";
    String mDescription = description.length() > 0 ? "%"  + description + "%" : "%";
    String mAmount = amount.length() > 0 ? "%"  + amount + "%" : "%";

    Log.d("Parameters",mDate + "," + mTime + "," + mCategory + "," + mDescription + "," + mAmount);

    return db.rawQuery( query, new String[] { mDate, mTime, mCategory, mDescription, mAmount } );
}
}

如果未传递任何值(所有字段均为“%”),则其中一个结果为此记录:

Date: 30/10/2016
Time: 6:56:41
Category: Food
Description: Lunch at Nosh
Amount: 25

但是,将描述指定为“unc”时,不会出现相同的记录。调试日志显示了预期的参数和SQL,所以我不确定为什么这不是结果。

SELECT * FROM expenses where createdDate like ? and createdTime like ? and category like ? and description like ? and amount like ?
[%,%,%,%unc%,%]

我缺少什么?

编辑:解决了问题

感谢@laalto我发现问题是由于同时有Cursor.moveToFirst和Cursor.moveToNext,因此搜索可能已经跳过了一个结果。

1 个答案:

答案 0 :(得分:1)

基于问题评论:查询很好,与预期的行匹配。

问题是阅读返回的Cursor。像

这样的结构
if (cursor.moveToFirst()) {
    while (cursor.moveToNext()) {
        //...
    }
}

跳过第一个结果行,这是唯一返回的具有更具体选择条件的行。

迭代游标的惯用模式是:

if (cursor.moveToFirst()) {
    do {
        //...
    } while (cursor.moveToNext());
}
相关问题