【问题标题】:I'm trying to get sum of column in SQLite database我正在尝试获取 SQLite 数据库中的列总和
【发布时间】:2021-03-23 10:30:22
【问题描述】:

我想得到列价格的总和,但总价显示为 -2

//Dbhandler
 public Cursor gettotalp()
{
    SQLiteDatabase database = this.getReadableDatabase();
    Cursor cursor =database.rawQuery("select sum(totalprice) as total from " + TABLE_Users + ";", null);
   Log.d(TAG, "gettotalp: "+cursor.getCount());
    return cursor;
}
//showallsaleitemActivity
 Cursor cursor = db.gettotalp();
    int m=0;
       /* while (cursor.moveToNext()) {
            m += cursor.getInt(cursor.getColumnIndex("totalprice"));
        }*/
    for(int k = 0; k<=cursor.getCount();k++) {
        m += (int) Integer.parseInt(String.valueOf(cursor.getColumnIndex("totalprice")));
    }
    int i=m;
        tp.setText("" + m);

database table image

【问题讨论】:

    标签: java android sqlite sum android-sqlite


    【解决方案1】:

    您的主要问题是游标中的列名与传递给getColumnIndex 方法的列名不匹配。

    其次你想要的值存储在Cursor的列中,它不是Cursor中列的索引值。由于它是第一个也是唯一的列,因此索引将为 0,而不是 totalprice 列的总和。相反,您需要使用 Cursor get???? 方法之一根据列的索引获取存储在列中的值,在这种情况下,您要使用 getIntgetString (如果您想使用该值进行计算,然后getInt 意味着您不必从字符串执行 parseInt,如果您只想显示该值,则可以使用 getString

    • 我个人更喜欢使用更适合所检索值类型的 get 方法来获取值。因此,因为它是一个整数值,所以我使用了getInt,即使它被用作字符串。

    我建议使用以下 2 个 sn-ps 代码:-

    // DBHanlder
    public int gettotalp() {
        int rv = 0;
        String total_column = "total_price";
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor cursor =database.rawQuery("select sum(totalprice) as " + total_column  + " from " + TABLE_Users + ";", null);
        Log.d(TAG, "gettotalp: "+cursor.getCount());
        if (cursor.moveToFirst()) {
            rv = cursor.getInt(cursor.getColumnIndex(total_column));
        }
        cursor.close();
        return rv;
    }
    
    • 使用变量作为列名别名可以减少出错的机会。
    • Cursor moveToFirst 方法将移动到 Cursor 的第一行。
      • 从创建游标的 SQLiteDatabase 方法返回游标时,游标位于第一行之前的位置,因此需要移动。
      • 如果无法进行移动,所有 Cursor move???? 方法都会返回 false。
    • 游标完成后应始终关闭。不这样做会导致错误的根本原因(例如文件句柄耗尽)难以确定。

    第二个片段:-

    //showallsaleitemActivity
    tp.setText(Integer.toString(gettotalp()));
    

    注意

    而不是使用

    cursor.getInt(cursor.getColumnIndex(total_column))
    

    因为你只返回一个你可以使用的值

    cursor.getInt(0)
    

    那么列名就无关紧要了(如果对 SQL 有效)。就个人而言,我更喜欢不使用硬编码索引,除非必要或过于复杂而不使用它们。

    【讨论】:

      【解决方案2】:

      在您的查询中返回总和的列不是totalprice
      您将其别名为total
      要获得它,请使用:

      Cursor cursor = db.gettotalp();
      cursor.moveToFirst()
      int m = cursor.getInt(cursor.getColumnIndex("total"));
      

      或者,由于查询只返回 1 列:

      int m = cursor.getInt(0);
      

      您不需要for 循环,它在您的代码中添加了两次-1 并返回-2,因为cursor.getColumnIndex("totalprice") 返回-1(因为该列不存在)。

      【讨论】:

        猜你喜欢
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多