使用数据库列值到Date()sqlite android时出现问题

时间:2018-10-28 10:52:12

标签: java android sqlite date android-sqlite


我有一个小问题,我用谷歌搜索了很多遍,但是我听不懂...
我正在使用查询(sqlite)检索一些数据..
在此查询中,它们的Date()用于增加某些日期动态天数(来自同一表的列)..
如果我把这几天设为静态(1,2,3,.....),它可以正常工作,但是如果我把列名放在那儿,就不行了。
此查询失败,我希望它能正常工作:

String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
            + DATE + " = date('" + targetDate + "',' " + REPETITIONS + " day') ";

这很好用:

String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
            + DATE + " = date('" + targetDate + "','2 day') ";

其中

  

targetDate:用户输入的获取该日期事件的日期

     

DATE:表中每个事件的日期

     

重复:动态数字(同一表中的列)

问题是在日期函数中使用了REPETITIONS ...

创建语句

String SQL_CREATE_EVENT_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " +
            ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            TITLE + " TEXT ," +
            DATE + " TEXT , " +
            IS_NOTIFY + " INTEGER , " +
            NOTIFICATION_TIME + " TEXT ," +
            REPEAT + " INTEGER ," +
            REPEAT_DURATION + " INTEGER ," +
            REPETITIONS + " INTEGER ," +
            CERTAIN_DATE + " TEXT ," +
            NOTE + " TEXT ," +
            IS_SPOKEN + " INTEGER " +
            " );";

这是选择语句

String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE " + DATE + " = '" + targetDate
            + "' OR (( " + REPEAT + " = '1' AND " + REPEAT_DURATION + " = '0' ) AND " + DATE + " <= '" + targetDate + "')"
            + " OR( " + REPEAT + " = '1' AND " + REPEAT_DURATION + " = '3' ) AND " + DATE + " <= '" + targetDate + "' AND " + CERTAIN_DATE + " >= '" + targetDate + "'"
            + " OR (" + REPEAT + " = '1' AND " + REPEAT_DURATION + "= '2' ) AND " + targetDate + " >= '" + DATE + "' AND "+ targetDate+ " <= date('" + DATE + "','" + REPETITIONS + " days')";

2 个答案:

答案 0 :(得分:1)

此语句中的变量REPETITIONS

String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
            + DATE + " = date('" + targetDate + "',' " + REPETITIONS + " day') ";

应该是数字,而不是列名。
SQLite中的date函数具有多种语法,但是您可以使用以下语法:

SELECT date('2014-10-23','+7 day');

您必须在day前提供一个数字。

编辑,请尝试以下操作:

String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
            + DATE + " = date('" + targetDate + "', " + REPETITIONS + " || ' day') ";

答案 1 :(得分:1)

在sqlite date() function中,NNN days是字符串修饰符,而不是表达式。因此,您不能在其中使用列名,甚至不能使用||字符串连接。

您可以在代码中设置修饰符字符串的格式,并将其放置在SQL中。这需要对数据库进行其他查询,而这可能不是您想要的。

如果您可以假设每天是24小时(并非总是如此,请考虑例如DST事件),您可以尝试

... date(strftime('%s', '" + targetDate + "', " + REPETITIONS + "*24*60*60, 'unixepoch') ...

其中strftime('%s', ...)转换为秒,而date(..., 'unixepoch')转换回日期戳。

但是认真的我会考虑重新设计架构以更好地支持您的功能需求。