我正在运行SQLite来为创建的执行选择两个范围之间的数据。要从两个日期之间选择数据,我使用以下语句
public ArrayList<LoopExecution> getDateRangeLoop(Date fromDate, Date toDate, int limit) {
String query = "SELECT * FROM"
+ " loopexe "
+ " WHERE "
+ " created_on "
+ " BETWEEN " + fromDate.getTime()
+ " AND " +toDate.getTime();
Cursor cursor = database.rawQuery(query, null);
ArrayList<LoopExecution> loopExecutions = new ArrayList<LoopExecution>();
if(cursor.moveToNext()) {
do {
LoopExecution loopExecution = new LoopExecution();
loopExecution.setId(cursor.getString(0));
Date createdOn = new Date(cursor.getLong(1));
loopExecution.setCreatedOn(createdOn);
loopExecution.setCreatedBy(cursor.getString(2));
loopExecution.setLoopId(cursor.getString(3));
loopExecution.setLoopStatus(LoopExecution.LoopStatus.valueOf(cursor.getString(4)));
loopExecution.setImage(cursor.getString(5));
loopExecution.setResultJson(cursor.getString(6));
loopExecution.setBgImage(cursor.getString(7));
loopExecution.setTrendImage(cursor.getString(8));
loopExecutions.add(loopExecution);
} while (cursor.moveToNext());
}
cursor.close();
return loopExecutions;
}
在SQLite数据库中创建查询
public static final String CREATE_LOOP_EXC_TABLE = CREATE_TABLE + LOOP_EXC_TABLE_NAME
+ "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ CREATED_ON + "TIMESTAMP , " + CREATED_BY + "VARCHAR , "
+ LOOP_ID + "VARCHAR , " + LOOP_STATUS + "INTEGER NOT NULL, "
+ LOOP_IMAGE + "VARCHAR NOT NULL, " + RESULT_JSON + "VARCHAR , "
+ LOOP_BG_IMAGE + "VARCHAR , " + LOOP_TREND_LINE + "VARCHAR , "
+ "FOREIGN KEY(created_by) REFERENCES user(id) , "
+ "FOREIGN KEY(loop_id) REFERENCES loop(id) " + ")";
答案 0 :(得分:0)
确保您的日期格式为 yyyy-MM-dd
尝试将日期放在 DATE()标记
中String query = "SELECT * FROM"
+ " loopexe "
+ " WHERE "
+ " created_on "
+ " BETWEEN DATE('" +fromDate.getTime() + "') "
+ " AND DATE('" + toDate.getTime() + "') ";
答案 1 :(得分:0)
Option one (if created_on
is of type INTEGER
):
Since you want to use the long timestamp (just a number), which getTime()
retrieves, you have to use the <
and >=
operators.
String query = "SELECT * FROM"
+ " loopexe "
+ " WHERE "
+ " created_on "
+ " >= " + fromDate.getTime()
+ " < " + toDate.getTime();
Option two (if created_on
is of type TEXT
):
You can use the BETWEEN
operator but then you need to specify its arguments in a different format.
String query = "SELECT * FROM"
+ " loopexe "
+ " WHERE "
+ " created_on "
+ " BETWEEN '2017-07-10'"
+ " AND '2017-07-14'";
This is just an example with hardcoded dates. To make it dynamic use:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String date = formatter.format(today);