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
参数中包含的所有内容都被视为字符串文字,并在将要执行的语句中被单引号包围
您可以阅读更多内容。您可以尝试设置不相等,但
或