在 Android 上用 Java 获取 SQLite SUM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1182831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetching a SQLite SUM in Java on Android
提问by Josef Pfleger
I'm new to SQLite and Java, and I'm trying to learn things on the fly. I have a column that has some numeric values in it, and I would like to get the sum of it and display it in a textview.
我是 SQLite 和 Java 的新手,我正在尝试即时学习。我有一个列,其中包含一些数值,我想获取它的总和并将其显示在文本视图中。
My current code is this:
我目前的代码是这样的:
public Cursor getTotal() {
return sqliteDatabase2.rawQuery(
"SELECT SUM(COL_VALUES) as sum FROM myTable", null);
}
I'm not sure if that code is correct, though.
不过,我不确定该代码是否正确。
I know that I'm supposed to fetch the results of that code, but I'm unsure how to do it. How can I get the results of this query into my Java code?
我知道我应该获取该代码的结果,但我不确定如何去做。我怎样才能把这个查询的结果放到我的 Java 代码中?
回答by Josef Pfleger
The sum will be returned as a result with one row and one column so you can use the cursor to fetch that value:
总和将作为一行和一列的结果返回,因此您可以使用游标来获取该值:
Cursor cursor = sqliteDatabase2.rawQuery(
"SELECT SUM(COL_VALUES) FROM myTable", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}

