简体   繁体   中英

deleting android SQLite rows older than x days

I want to delete all rows in table MYTABLE which are older than x days. Column SAVE_DATE Long is the time when the row was inserted in table.

I tried this but apparently it deletes all my rows:

long daysInMiliSec = new Date().getTime() - X
            * (24L * 60L * 60L * 1000L);
return db.delete(MYTABLE , SAVE_DATE
            " <= ?", new String[] { "" + daysInMiliSec }

What is wrong?

Below query will delete data older than 2 days:

String sql = "DELETE FROM myTable WHERE Save_Date <= date('now','-2 day')"; 
db.execSQL(sql);

Since it's the first hit on google some more explanation for beginners:
You do not need the time/date functions from the main program you use to access the sqlite DB but use the sqlite date functions directly.

You create the table with the row entry for the age with for example:

CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, text TEXT, age INTEGER)

You write to it with

INSERT INTO test (text, age) VALUES ("bla", datetime('now'))

Here I used 'datetime' because this also will let you later search for hours/minutes/seconds. If you don't need that 'date('now')' is enough.

Here is an explanation for the date function: https://www.sqlite.org/lang_datefunc.html

To select everything older than for example 5 minutes:

SELECT * FROM test WHERE age <= datetime('now', '-5 minutes')

You can see more of those possibilities on the website above under the paragraph ' Modifiers '.

删除时间戳或日期字段存储时间超过2天的数据(以毫秒为单位)或一个纪元整数。

DELETE FROM update_log WHERE timestamp <= strftime('%s', datetime('now', '-2 day'));

With the latest version of ORMLite for SQLite Android: http://ormlite.com/sqlite_java_android_orm.shtml , you may achieve this by using the following code:

                        String sql = "DELETE FROM graph WHERE time <= 1522405117";
                        dbHelper.getWritableDatabase().execSQL(sql);

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