【发布时间】:2013-09-12 17:43:47
【问题描述】:
我的 Android 项目中有一个 sqlite DB,我尝试选择日期之间的所有行。 但是这个查询没有返回任何行:
String where = OperationEntry.COLUMN_NAME_ENTRY_ACCOUNT_FK + " = ? AND " +
OperationEntry.COLUMN_NAME_ENTRY_DATE + " > date('2013-01-01') AND "+
OperationEntry.COLUMN_NAME_ENTRY_DATE + " < date('2013-12-31') ;";
String[] whereValue = {accountName};
Cursor c = db.query(
OperationEntry.TABLE_NAME, // The table to query
projection, // The columns to return
where, // The columns for the WHERE clause
whereValue, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
此外,如果我使用 2013-01-01 和 2014-12-31,所有行都匹配。
我已经测试了有无日期功能,我有同样的问题。
请注意 OperationEntry.COLUMN_NAME_ENTRY_DATE 是 Date 类型。
你能帮帮我吗?你发现我的代码有什么错误吗?
谢谢
乔纳森。
编辑: 我在这里放了一些额外的代码。 查询建表:
public static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + OperationEntry.TABLE_NAME + " (" +
OperationEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
... +
OperationEntry.COLUMN_NAME_ENTRY_DATE + " DATE, " + ...
" )";
插入查询:
GregorianCalendar calendar = ...;
String date = calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
ContentValues values = new ContentValues();
values.put(OperationEntry.COLUMN_NAME_ENTRY_TITLE, operation.getTitle());
values.put(OperationEntry.COLUMN_NAME_ENTRY_QTE, operation.getQte());
values.put(OperationEntry.COLUMN_NAME_ENTRY_DATE, date);
...
long newRowId;
newRowId = db.insert(
OperationEntry.TABLE_NAME,
null,
values);
【问题讨论】:
-
输入日期列中的值的格式是什么? (SQLite 没有
Date类型。) -
我刚刚添加了一些代码:如您所见,它是创建查询中的日期类型,但我输入了字符串。我会尽快尝试使用 TEXT 类型。
-
将
calendar.get(Calendar.MONTH)转换为字符串不能保证得到两位数。 -
正确:现在确定问题是逐字母比较:“8”(9 月)>“1”(12 月 12 日)。现在这不是更好的解决方案,但我会尝试用两位数强制日期和月份,如果没有其他解决方案,我会用字符串类型替换 Date 类型