无法弄清楚为什么SQL语句不起作用

时间:2014-08-12 01:21:12

标签: java android sql sqlite

我无法理解我的陈述有什么问题。看起来对我来说,光标应该包括我的数据库表中的两行。根据SQLite网站,支持这种格式化的日期(也尝试使用其他支持的日期)。

        String statement = "SELECT * FROM " + TABLE_DISTANCE_NAME + " WHERE " + COLUMN_TIME_DISTANCE_ADDED + " BETWEEN " + "2014-07-14" + " AND " + "2014-08-14";
        Log.d("statement", statement);
        Cursor cur = db.rawQuery(statement, null);
        Log.d("cursor amount rows", Integer.toString(cur.getCount()));

        if (cur != null) {
            cur.moveToFirst();
        }    
        int totalDistance = 0;
        while (cur.isAfterLast() == false) {
            Log.d("cursor distance value", Integer.toString(cur.getInt(0)));
            totalDistance += cur.getInt(0);
            cur.moveToNext();
        }
        Log.d("Total Distance traveled = ", Integer.toString(totalDistance));

这就是表格的样子。 This is what my table looks like

日志:

...statement﹕ SELECT * FROM distanceTraveled WHERE timedistadded BETWEEN 2014-07-14 AND 2014-08-14

com.example.RoadTrip D/cursor amount rows﹕ 0
com.example.RoadTrip D/Total Distance traveled =﹕ 0

谢谢

2 个答案:

答案 0 :(得分:3)

日期常量需要用单引号括起来:

" WHERE " + COLUMN_TIME_DISTANCE_ADDED + " BETWEEN " + "'2014-07-14'" + " AND " + "'2014-08-14'";

如果在替换后打印出SQL语句,则此问题会更加明显。这是尝试调试此类问题的第一步。

答案 1 :(得分:1)

尝试引用查询参数

e.g。

+ "'2014-07-14'" + " AND " + "'2014-08-14'"

日期和字符串需要按照SQL单引号。