创建表格
public static void createTable(SQLiteDatabase db){
String sql = "CREATE TABLE " + TABLE_HISTORY + " ("
+ COL_ID + " INTEGER PRIMARY KEY NOT NULL, "
+ COL_TITLE + " TEXT, "
+ COL_MEDIA_NAME + " TEXT, "
+ COL_IMAGE_URL + " TEXT, "
+ COL_URL + " TEXT, "
+ COL_CREATED_AT + " INTEGER NOT NULL DEFAULT 0, "
+ COL_UPDATED_AT + " INTEGER NOT NULL DEFAULT 0 "
+ ")";
db.execSQL(sql);
}
INSERT TABLE
public static long insertTableHistory(DatabaseDAO db, int mId, String title, String mediaName, String imageUrl, String url) {
SQLiteDatabase database = db.getWritableDatabase();
String sql =
"INSERT INTO " + TABLE_HISTORY + " ("
+ COL_ID + ", "
+ COL_TITLE + ", "
+ COL_MEDIA_NAME + ", "
+ COL_IMAGE_URL + ", "
+ COL_URL + ", "
+ COL_CREATED_AT + ","
+ COL_UPDATED_AT +
")"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
SQLiteStatement statement = database.compileStatement(sql);
long id = -1;
try {
database.beginTransaction();
statement.clearBindings();
statement.bindLong(1, mId);
statement.bindString(2, title);
statement.bindString(3, mediaName);
statement.bindString(4, imageUrl);
statement.bindString(5, url);
statement.bindLong(6, System.currentTimeMillis());
statement.bindLong(7, System.currentTimeMillis());
id = statement.executeInsert();
database.setTransactionSuccessful();
} catch (Exception e) {
database.endTransaction();
} finally {
database.endTransaction();
}
return id;
}
我试试 但它不起作用。
public static void deleteDataOlderThan30Days(DatabaseDAO databaseDAO) {
String sql = "DELETE FROM " + TABLE_HISTORY + " WHERE " + COL_CREATED_AT + "<= date('now','-30 day')";
SQLiteDatabase database = databaseDAO.getWritableDatabase();
database.execSQL(sql);
}
如何删除超过30天的HistotyTable的所有数据?
请。救救我!
答案 0 :(得分:2)
您的时间戳列包含一个数字,即1970年以来的毫秒数。
date
函数返回格式为yyyy-mm-dd
的字符串。
更改数据库以相同格式存储时间戳,或更改查询以毫秒格式计算日期限制:
... WHERE CreatedAt <= strftime('%s', 'now', '-30 days') * 1000
答案 1 :(得分:-1)
使用的约会功能
说到SQL,你必须指定你的意思&#34;比一天更早&#34;。
DATEDIFF:它使用午夜边界,所以在10月19日00:05运行它,你将删除6分钟的行(10月18日23:59)
24小时?
昨天午夜? 10月19日运行代码,在18日之前删除行?
另外,不要在列上放置函数。
这假设24小时到达:
DELETE MyTableWhere 哪里 MyColumn&lt; DATEADD(day,-1,GETDATE()) 这假设是昨天午夜:
DELETE MyTableWhere 哪里 MyColumn&lt; DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()), - 1)