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

问题描述 投票:2回答:1

假设我有一个包含如下表格的数据库: CREATE TABLE tbl_EX (_id TEXT, 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);

之后,我尝试查询。没有WHERE条款:

database.query("tbl_EX", new String[]{"_id", "TIME"}, null, null, null, null, "TIME");

它按预期检索了我的所有记录,它们显示在2 TextView中,如下所示:

_id = SomeID | Time = 2019-03-30 15:00:00

但是,当我用这个WHERE条款进行查询时:

database.query("tbl_EX", new String[]{"_id", "TIME"}, "date(TIME) = ?", new String[]{"date('now')"}, null, null, "TIME");

没有找到数据!我甚至尝试将部分new String[]{"date('now')"}替换为 new String[]{"date('2019-03-30')"}or new String[]{"strftime('%Y-%m-%d', 'now')"}甚至 new String[]{"'2019-03-30'"},仍然没有去。 那么,我是否以正确的方式将DateTime数据存储在SQLite数据库中?并以正确的方式查询它?

android sqlite android-sqlite
1个回答
1
投票

当你通过

new String[]{"date('now')"}

作为参数,这被转换为此查询:

select _id, TIME from tbl_EX where date(TIME) = 'date('now')'

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

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参数中包含的所有内容都被视为字符串文字,并且实际上将被将要执行的语句中的单引号括起来。 你可以阅读更多here

© www.soinside.com 2019 - 2024. All rights reserved.