如何从今天的日期和7天时间之间的SQLite表中选择行

时间:2015-08-19 11:27:03

标签: sql sqlite



public class DbHelper extends SQLiteOpenHelper {
  
    private static final String DATABASE_NAME = "assignment_info.db";

    public static final String ASSIGNMENT_ID  = "_id";
    public static final String ASSIGNMENT_VALUE = "assignment_value";
    public static final String ASSIGNMENT_RESULT = "assignment_result";
    public static final String SUBJECT = "subject";
    public static final String ASSIGNMENT_TITLE = "assignment_title";
    public static final String DUE_DATE = "due_date";
    public static final String NOTES_ASSIGNMENT = "notes";
    public static final String TABLE_NAME_ASSIGNMENT = "assignment_information";

    private static final String ADD_QUERY = "CREATE TABLE "+
            TABLE_NAME_ASSIGNMENT+"("+
            ASSIGNMENT_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+
            SUBJECT+" TEXT,"+
            ASSIGNMENT_VALUE+" INTEGER,"+
            ASSIGNMENT_RESULT+" DOUBLE,"+
            ASSIGNMENT_TITLE+" TEXT,"+
            DUE_DATE+" DATE,"+
            NOTES_ASSIGNMENT+" TEXT);";


    public DbHelper(Context context){

        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        Log.e("Database Operations","Database opened/created from constructor.");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //IF DATABASE IS CREATED FOR FIRST TIME THIS METHOD WILL BE CALLED
        db.execSQL(ADD_QUERY);
        db.execSQL(ADD_NOTES_QUERY);
        Log.e("Database Operations"," DbHelper - onCreate called ");

    }




我有一个SQLite表,其中包含存储为字符串>>
的日期 " + DUE_DATE +" STRING," 。

我想选择今天日期和现在7天之间的所有行。

这是我到目前为止所做的,它不会返回任何结果,

    String sql = "SELECT * FROM " + TABLE_NAME_ASSIGNMENT + " WHERE "+ DUE_DATE + " >= date('now') AND date('now','+7 days')";

任何人都可以帮忙吗? 感谢

创建表TABLE_NAME_ASSIGNMENT     (ASSIGNMENT_ID INT,SUBJECT文字,ASSIGNMENT_TITLE文字,DUE_DATE日期) ;

插入TABLE_NAME_ASSIGNMENT     (ASSIGNMENT_IDSUBJECTASSIGNMENT_TITLEDUE_DATE) VALUES     (1,' MATHS',' Prime Numbers',' 2015-08-22'),     (2,'科学','周期表',2015-08-30'),     (3,' MATHS',' Odd Numbers',' 2015-09-02') ;

选择   *

这   TABLE_NAME_ASSIGNMENT

截止日期('现在')和日期('现在',' +7天')

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以获得正确的语法,以便在' + 7天后使用')'在第10行

2 个答案:

答案 0 :(得分:1)

您是否尝试过使用BETWEEN?

String sql = "SELECT * FROM " + TABLE_NAME_ASSIGNMENT + " WHERE "+ DUE_DATE + " BETWEEN date('now') AND date('now','+7 days')"

还要确保DUE_DATE是YYYY-MM-DD格式的DATE类型

答案 1 :(得分:0)

在表中,您将日期存储为字符串类型,因此除非在执行查询时以实际日期格式转换日期字符串,否则无法以传统方式检索数据。 请使用以下查询再试一次。

SELECT 
 * 
FROM 
 Mytable 
WHERE 
 DATE(substr(fecha ,1,4) ||substr(fecha ,6,2)||substr(fecha ,9,2))
BETWEEN 
 DATE(20140105) 
AND 
 DATE(20140105);