根据日期和其他参数从 sqlite 中删除数据 android

deleting data from sqlite based on date and other paramter android

我正在尝试根据某些条件(尤其是基于日期)从 table 中删除一些行。

我有 tables 包含字符串类型和其他字段的日期,这是我的 table 结构

 private static final String DATABASE_CREATE_HISTORY = "CREATE TABLE " + TABLE_HISTORY + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT," +  COLUMN_LOC + " TEXT," +  COLUMN_TYPE + " TEXT," + COLUMN_DATE + " TEXT" + ")";

现在我想删除所有基于日期和 COLUMN_LOC

的行

这是我正在做的

  int numDeleted = database.delete(DataBaseHelper.TABLE_HISTORY, "date" + " < '" + writeFormat.format(d) + "'" + " AND " + DataBaseHelper.COLUMN_LOC  + " = " +location, null);

在上面的查询中,日期是这种格式 Sat Mar 21 00:00:00 GMT+01:00 2015 并且 COLUMN_LOC 是包含例如 "Home"、"Airport" 等的字符串

但是应用程序在这个删除操作上崩溃并出现错误

android.database.sqlite.SQLiteException: no such column: Home (code 1): , while compiling: DELETE FROM history WHERE date < 'Sat Mar 21 00:00:00 GMT+01:00 2015' AND loc = Home

我不明白为什么它在行中包含主页字段并且没有 COLUMN_LOC 参数它工作正常。

看最后SQL:

DELETE FROM history WHERE date < 'Sat Mar 21 00:00:00 GMT+01:00 2015' AND loc = Home

您尝试将 loc 列与 Home 列进行比较。

正确的代码是

int numDeleted = database.delete(DataBaseHelper.TABLE_HISTORY, "date" + " < '" + writeFormat.format(d) + "'" + " AND " + 
DataBaseHelper.COLUMN_LOC  + " = '" +location + "'", null);

更新

为了比较正确的日期:

  1. Table 创建:

    DATABASE_CREATE_HISTORY = "CREATE TABLE " + TABLE_HISTORY + "(" + COLUMN_ID + "整数主键," + COLUMN_NAME + "文本," + COLUMN_LOC + " TEXT," + COLUMN_TYPE + " TEXT," + COLUMN_DATE + " INTEGER" + ")";

  2. 正在删除:

    int numDeleted = database.delete(DataBaseHelper.TABLE_HISTORY, "date" + " < " + d.getTime() + " AND " + DataBaseHelper.COLUMN_LOC + " = '" +location + "'", null);

SQL 中的字符串文字需要在 'single quotes' 中引用,并且由于 Home 未被引用,它被解析为列名。

考虑对文字使用 ? 占位符,并将值与 selectionArgs 绑定。

还可以考虑使用自然排序也是按时间顺序排序的日期格式,例如 unixtime 或 ISO 8601。< 'Sat Mar 21 00:00:00 GMT+01:00 2015' 将匹配按字母顺序小于日期值的行。