简体   繁体   中英

Service to delete entries in SQLite db that is older than x days

I have a Service which will clean up some files, and execute some SQL queries. This specific SQL query should delete entries which is older than x days. My method to do so, is this:

public boolean deleteOldCases(int days) {

        String deleteQuery = "DELETE FROM " + TABLE_CASES + " WHERE " + DATE +  " <= date('now','-" + days + " day')";
        Log.d("Delete Query: ", deleteQuery);
        SQLiteDatabase db = this.getWritableDatabase(); 
        db.rawQuery(deleteQuery, null);
        db.close();

        return true;
    }

When am adding entries to my database, I do it like this:

public void addCase(Case c) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, c.getCaseNumber());
        values.put(STATUS, "");

        // Inserting Row
        db.insert(TABLE_CASES, null, values);

        db.execSQL("Update " + TABLE_CASES + " Set " + DATE + "=datetime() where " + KEY_ID + "= '" + c.getCaseNumber() + "';" );

        db.close(); // Closing database connection

    }

This method is called from my service, and I can verify by logging that this method is called. All of these data is displayed to the user in a ListView, which obviously works. But the old entries are not deleted at all..

I suspect that it's because I save the case with the date = datetime() and trying to remove it with <=date('now', '-1 day')

Can someone see what am doing wrong?

Use rawQuery() only for real queries (SQL-statements starting with "SELECT" keyword). Use execSql() instead.

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