问题描述
我已按照以下答案设置了数据库:如何在Flutter中使用SQFlite进行数据库查询,但我想获取要创建的数据库列中所有项目的总和,然后在TextLabel上显示该数字.我查看了但无法找到有关可以在哪里找到解决方案的任何信息
I have setup a database following this answer: How to do a database query with SQFlite in Flutter but I want to get the sum of all the items in a column for the database I'm creating and then display that number on a TextLabel. I've looked but not able to find any information on where I could find a solution to this
推荐答案
SQFlite就像SQLite具有聚合函数并执行sum函数,您可以将其作为rawQuery进行如下操作:
SQFlite just like SQLite has Aggregate Functions and to execute a sum function you can do it as a rawQuery as follows:
Future<int> sumItems() async {
final sum = await db.rawQuery("SELECT sum(id_word) as sum FROM Word");
//print(sum[0]["sum"]);
return sum[0]["sum"];
}
要在文本"小部件中使用此函数的结果,只需使用 FutureBuilder .
To use the result of this function in your Text widget, you just have to use a FutureBuilder.
此外,如果您想使用WHERE句子或Group By句子之类的参数,只需将其作为参数传递给数组即可.
Additionally if you want to use arguments like a WHERE sentence or a Group By sentence, just add it an pass the arguments as an array.
final sum = await db.rawQuery("SELECT sum(id_word) as sum FROM Word WHERE id_word = ?", [5]);
这篇关于如何使用Flutter sqflite查询SQL Lite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!