【问题标题】:Android SQLite Query between Dates not working日期之间的Android SQLite查询不起作用
【发布时间】:2018-04-24 16:54:20
【问题描述】:

我必须从表中获取所有记录数。我的方法如下:

  public int getTasksByStatusIDBetweenDates(int statusID, String startDate, String endDate) {

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(
            "select * from Task" +
                    " where StatusID=" + statusID + " and AssignDate between '" + startDate + "' and '" + endDate + "'", null);

    int total = 0;
    if (cursor.moveToFirst())
        total = cursor.getInt(0);

    cursor.close();
    return total;
}  

目前它返回我 0。我的日期格式是 "yyyy-MM-dd HH:mm:ss"

请指导我哪里做错了。谢谢!

【问题讨论】:

  • 你在哪里调用这个方法?你能发布我提到的代码吗?
  • @noman-hamid : 存储在您的数据库中的日期格式是否与您争论的日期格式相同 startDate 和 endDate ???
  • @AntónioPaulo 我只是在我的活动中从该函数中获取计数和整数变量。但是我从这个查询中得到的计数是 0。
  • cursor.getInt(0),你要获取表格的第一列值吗??
  • 我猜你应该用datetime()函数包装时间字符串变量

标签: android sqlite


【解决方案1】:

或现有代码只需调用cursor.getCount();

total=cursor.getCount();

Cursor.getCount();
返回游标中的行数。

更新
查询以获取 b/w 两个日期的记录 SO - How to select data between two date range in android SQLite

查询是
SELECT * FROM mytab where my_date BETWEEN '2016-03-01 00:00:00' AND '2016-03-19 00:00:00'

【讨论】:

  • 是的,我试过了。告诉我一件事,我在表中使用 AssigneDate 数据类型作为文本.. 可以吗?或者我必须使用 DATETIME 数据类型?
  • 对我来说,TEXT 类型工作正常。但是也尝试使用 DateTime。
  • 酷..你能分享你的全部功能吗?
  • 谢谢,我会尝试的..我必须在网格视图中显示...记录是所有月份的,所以我必须相应地应用过滤器..这就是我在查询中传递日期的原因。
【解决方案2】:

我认为您应该使用 COUNT(*) 而不仅仅是 *。

试试这个。

public int getTasksByStatusIDBetweenDates(int statusID, String startDate, String endDate) {

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(
            "select count(*) from Task" +
                    " where StatusID=" + statusID + " and AssignDate between '" + startDate + "' and '" + endDate + "'", null);

    int total = 0;
    if (cursor.moveToFirst())
        total = cursor.getInt(0);

    cursor.close();
    return total;
}  

【讨论】:

    【解决方案3】:

    带有SELECT * 的查询返回表中所有行的所有列。

    cursor.getInt(0)返回游标当前行第一列的值。

    要计算行数,您可以使用带有SELECT COUNT(*) ... 的查询,并读取其返回的值。或者,使用有用的helper function 为您构建查询:

    public int getTasksByStatusIDBetweenDates(int statusID, String startDate, String endDate) {
        SQLiteDatabase db = this.getReadableDatabase();
        return DatabaseUtils.queryNumEntries(
                db, "Task",
                "StatusID=" + statusID + " and AssignDate between ? and ?",
                new String[]{ startDate, endDate });
    }  
    

    【讨论】:

    • 试过了..不工作..我表中的AssignedDate是文本。
    猜你喜欢
    • 2014-09-22
    • 2020-07-06
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多