Android SQLite-查询将DateTime与WHERE子句进行比较的任何行时,DateTime格式存在问题

Android SQLite-查询将DateTime与WHERE子句进行比较的任何行时,DateTime格式存在问题,android,sqlite,android-sqlite,Android,Sqlite,Android Sqlite,假设我有一个数据库,其中包括这样一个表: CREATE TABLE tbl_EX(_idtext,TIME TEXT) 然后我插入如下值: Date currentTime = Calendar.getInstance(Locale.getDefault()).getTime(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String time

假设我有一个数据库,其中包括这样一个表:
CREATE TABLE tbl_EX(_idtext,TIME TEXT)
然后我插入如下值:

Date currentTime = Calendar.getInstance(Locale.getDefault()).getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String time = dateFormat.format(currentTime);
ContentValues contentValues = new ContentValues();
contentValues.put("_id", "SomeID");
contentValues.put("TIME", time);
database.insert("tbl_EX", null, contentValues);
_id = SomeID | Time = 2019-03-30 15:00:00
在那之后,我试着询问。无
WHERE
子句:

database.query("tbl_EX", new String[]{"_id", "TIME"}, null, null, null, null, "TIME");
database.query("tbl_EX", new String[]{"_id", "TIME"}, "date(TIME) = ?", new String[]{"date('now')"}, null, null, "TIME");
它按预期检索了所有记录,这些记录显示在2文本视图中,如下所示:

Date currentTime = Calendar.getInstance(Locale.getDefault()).getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String time = dateFormat.format(currentTime);
ContentValues contentValues = new ContentValues();
contentValues.put("_id", "SomeID");
contentValues.put("TIME", time);
database.insert("tbl_EX", null, contentValues);
_id = SomeID | Time = 2019-03-30 15:00:00
但是,当我用这个
WHERE
子句进行查询时:

database.query("tbl_EX", new String[]{"_id", "TIME"}, null, null, null, null, "TIME");
database.query("tbl_EX", new String[]{"_id", "TIME"}, "date(TIME) = ?", new String[]{"date('now')"}, null, null, "TIME");
没有找到任何数据!我甚至尝试将
新字符串[]{“日期('now')”}
替换为
新字符串[]{“日期('2019-03-30')”}

新字符串[]{“strftime('%Y-%m-%d','now')”}
甚至
新字符串[]{“2019-03-30'”}
,仍然没有成功。

那么,我是否以正确的方式将日期时间数据存储在SQLite数据库中?并以正确的方式查询它???

当您通过时

new String[]{"date('now')"}
作为参数,这将转换为此查询:

select _id, TIME from tbl_EX where date(TIME) = 'date('now')'
你能看到问题吗?
date('now')
被视为
WHERE
子句的字符串参数,因此您的查询在
TIME
列中搜索文本
date('now')
你应该做的是:

database.query("tbl_EX", new String[]{"_id", "TIME"}, "date(TIME) = date(?)", new String[]{"now"}, null, null, "TIME");
这样将传递参数
now
,您的查询将为:

select _id, TIME from tbl_EX where date(TIME) = date('now')
类似地,当您想筛选特定日期,如
2019-03-30
时,必须执行以下操作:

database.query("tbl_EX", new String[]{"_id", "TIME"}, "date(TIME) = ?", new String[]{"2019-03-30"}, null, null, "TIME");
因此,您通过了
2019-03-30
,没有单引号

selectionArgs
参数中包含的所有内容都被视为字符串文字,并在将要执行的语句中被单引号包围


您可以阅读更多内容。

您可以尝试设置不相等,但