简体   繁体   中英

How to select records where date is between date1 and date2?

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);

I have tried with CAST, strftime, datetime. The due_date column is of varchar type and i want to select records having due_date between beginDate and endDate. All the dates are of dd/MM/yyyy format

If you change the column's DUE_DATE format to YYYY-MM-DD , which is the only comparable format for SQLite, then all you need is a BETWEEN clause and pass all the arguments as a string array, which is the recommended safest way to avoid any risk of sql injection:

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}
);

Of course the arguments beginDate and endDate must also be in the YYYY-MM-DD format.

You can use following query

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM