我试图根据某些条件从表中删除某些行,特别是基于日期。
我有包含字符串类型和其他fielde的日期的表,这是我的表结构
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
我没有说明为什么因为它包含Home fiels in row并且没有COLUMN_LOC参数它工作正常。
答案 0 :(得分:1)
SQL中的字符串文字需要在'single quotes'
中引用,并且由于未引用Home
,因此将其解析为列名。
考虑将?
占位符用于文字,并使用selectionArgs
绑定值。
还要考虑使用日期格式,其中自然排序也是按时间顺序排序,例如unixtime或ISO 8601. < 'Sat Mar 21 00:00:00 GMT+01:00 2015'
将匹配日期中字母小于值的行。
答案 1 :(得分:0)
查看最终的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);
<强>更新强>
正确的日期比较:
创建表:
DATABASE_CREATE_HISTORY =&#34;创建表&#34; + TABLE_HISTORY +&#34;(&#34; + COLUMN_ID +&#34; INTEGER PRIMARY KEY,&#34; + COLUMN_NAME +&#34; TEXT,&#34; + COLUMN_LOC +&#34; TEXT,& #34; + COLUMN_TYPE +&#34; TEXT,&#34; + COLUMN_DATE +&#34; INTEGER&#34; +&#34;)&#34;;
删除:
int numDeleted = database.delete(DataBaseHelper.TABLE_HISTORY,&#34; date&#34; +&#34;&lt;&#34; + d.getTime()+&#34; AND&#34; + DataBaseHelper.COLUMN_LOC +&#34; =&#39;&#34; + location +&#34;&#39;&#34;,null);