【问题标题】:SQLite - Problem with DateTime format when query any row comparing DateTime into WHERE clauseSQLite - 查询将 DateTime 与 WHERE 子句进行比较的任何行时,DateTime 格式存在问题
【发布时间】:2022-01-18 21:54:07
【问题描述】:

假设我有一个包含如下表的数据库:
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')"}
new String[]{"strftime('%Y-%m-%d', 'now')"} 甚至
new String[]{"'2019-03-30'"},仍然不行。

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

【问题讨论】:

  • 如果您确定搜索正确的字符串,您可以尝试设置不相等,但><。您也可以尝试在您知道的任何 SQLite 浏览器中打印date('2019-03-30') 或其他句子(参见sqlitebrowser.org)。

标签: java android sqlite date android-sqlite


【解决方案1】:

当你通过时

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

你可以阅读更多here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2018-04-13
    • 2016-08-06
    相关资源
    最近更新 更多