SQLite:按月从列中选择

时间:2018-12-19 13:47:20

标签: sqlite android-sqlite

我试图根据月份对一个表列求和,但出现以下异常:

   java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

功能

public static float test(SQLiteDatabase db) {

    String expenditure = MyDatabaseContract.TableExpenditure.ATTR_EXPENDITURE;
    String table = MyDatabaseContract.TableExpenditure.TABLE_EXPENDITURE;
    String date = MyDatabaseContract.TableExpenditure.ATTR_DATE;

    String query = "SELECT SUM(" + expenditure + ") FROM " + table + " WHERE strftime('%m', date)=11";
    Cursor cursor = db.rawQuery(query, null);


    float total = 0;
    if (cursor.moveToFirst())
        total = cursor.getInt(cursor.getColumnIndex("Total"));// get final total

    return total;
}

表格

public static class TableExpenditure {

    public static final String TABLE_EXPENDITURE = "expenditure_table";

    public static final String ATTR_PRIMARY_KEY = "pk_expendituretable";
    public static final String ATTR_DATE = "date";
    public static final String ATTR_CATEGORY = "category";
    public static final String ATTR_EXPENDITURE = "expenditure";
    public static final String ATTR_COMMENT = "comment";

    public static final int N_COLUMNS = 5;

    public static final String SQL_CREATE_TABLE =
            "CREATE TABLE " + TABLE_EXPENDITURE + "(" + ATTR_PRIMARY_KEY + " INTEGER PRIMARY KEY AUTOINCREMENT," +  ATTR_DATE + " DATE," + ATTR_CATEGORY + " TEXT," +
                    ATTR_EXPENDITURE + " REAL," + ATTR_COMMENT + " TEXT"  + ")";
}

在调试器中,光标包含一项,但是在调用getInt(..)时,应用程序崩溃了

1 个答案:

答案 0 :(得分:1)

为此结果创建的列:

SUM(" + expenditure + ")

不称为Total
将sql语句更改为此:

String query = "SELECT SUM(" + expenditure + ") AS Total FROM " + table + " WHERE strftime('%m', date)=11";

通过这种方式,您将名称(别名)Total赋予该列。
或者,由于仅返回1列,因此请执行以下操作:

total = cursor.getInt(0);