如何选择日期介于date1和date2之间的记录?

时间:2019-04-16 10:49:38

标签: android sqlite

SQLiteDatabase db = DatabaseProvider.dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("Select * from " + ConsumerEnquiryTable.TABLE_NAME + " where "
            + ConsumerEnquiryTable.Cols.USER_LOGIN_ID + "='" + userId + "' AND ( CAST("
            + ConsumerEnquiryTable.Cols.DUE_DATE + " as datetime) >= CAST(" + beginDate  +
            " as datetime) AND CAST(" + ConsumerEnquiryTable.Cols.DUE_DATE + " as datetime) <= CAST("+ endDate + " as datetime)) AND "
            + ConsumerEnquiryTable.Cols.CARD_STATUS + "='" + jobCardStatus + "'", null);

我尝试使用CAST,strftime,datetime。 due_date列是varchar类型,我想选择在beginDate和endDate之间具有due_date的记录。所有日期均为dd / MM / yyyy格式

2 个答案:

答案 0 :(得分:1)

如果将列的DUE_DATE格式更改为YYYY-MM-DD,这是SQLite唯一可比较的格式,那么您只需要一个BETWEEN子句并将所有参数作为字符串传递数组,这是建议的最安全的方法,可以避免sql注入的任何风险:

Cursor cursor = db.rawQuery(
    "SELECT * FROM " + ConsumerEnquiryTable.TABLE_NAME + " WHERE " + 
    ConsumerEnquiryTable.Cols.USER_LOGIN_ID + " = ? AND (" +
    ConsumerEnquiryTable.Cols.DUE_DATE + " BETWEEN ? AND ?) AND " +
    ConsumerEnquiryTable.Cols.CARD_STATUS + " = ?", 
    new String[] {userId, beginDate, endDate, jobCardStatus}
);

当然,参数beginDate和endDate也必须采用YYYY-MM-DD格式。

答案 1 :(得分:0)

您可以使用以下查询

mDb.query(MY_TABLE, null, DATE_COL + " BETWEEN ? AND ?", new String[] {
                minDate + " 00:00:00", maxDate + " 23:59:59" }, null, null, null, null);