为什么SQLite不选择今天的日期和月份?

时间:2020-05-07 10:16:35

标签: android database sqlite android-sqlite

我具有以下数据库结构

db.execSQL("create table " + TABLE_NAME + " (id integer primary key autoincrement,fname text default null, bday text)");

数据表

enter image description here

尝试选择具有今天和月份的记录。但是它总是返回0。这是什么问题?

public Cursor selectTodaysBday() {

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select fname from " + TABLE_NAME + " where strftime('%m',bday) = strftime('%m',date('now')) and strftime('%d',bday) = strftime('%d',date('now'))", null);

        Log.i("app", "todays count: " + cursor.getCount()); //always returning 0, i have 5 records of todays day and month

        return cursor;
}

请帮助我解决此问题。

1 个答案:

答案 0 :(得分:0)

查询不起作用的唯一方法是日期不具有YYYY-MM-DD格式,这是SQLite唯一有效的日期格式。
如果是这种情况,那么strftime()返回null,您不会从查询中获得任何行。
将日期格式更改为YYYY-MM-DD,还可以将查询简化为:

Cursor cursor = db.rawQuery(
    "select fname from " + TABLE_NAME + " where strftime('%m-%d',bday) = strftime('%m-%d',date('now'))", 
    null
);

没有理由分别检查月份和日期。

相关问题