简体   繁体   中英

How to get the number of rows in a database table with Flutter SQFlite

How do I get the row count of a database table in Flutter. I am using the SQFlite plugin.

I assume that it is similar to Android, but Android has DatabaseUtils.queryNumEntries(db, TABLE_NAME) . Does SQFlite have something similar?

I am answering the question to the best of my knowledge below, but I would be glad for a better answer if there is one.

You can use

int count = Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM table_name'));

where db is an SQFlite Database .

Source: I found this here and in the source code .

Try this function:

Future<int> getCount() async {
    //database connection
    Database db = await this.database;
    var x = await db.rawQuery('SELECT COUNT (*) from 
    $Table');
    int count = Sqflite.firstIntValue(x);
    return count;
}

No more hard function invocations needed. just try with .length If you are using a data model you can use its' name at MODEL_NAME .

Future<int> getCount() async {

Database db = await this.database;
var result = await db.query(MODEL_NAME.TABLE_NAME);
int count = result.length;
return count;

}

I believe a better way to do this is inside the DatabaseHelper/Service class :

class DbService {
  static Database _db; //static = only a single copy of _db is shared among all the instances of this class (Database)
  static int _count;

  static int get count => _count;
  ...

this way every time a query gets executed the count updates, this also makes it possible to update the count on queries with filters without having to write a new function for it 😎:

  List<Map> result = await db.query('myDatabase');
  _count = result.length;
  return result;
}

and then simply use DbService.count to get the count

You can also use

List<Map> list = await db.rawQuery('SELECT * FROM table_name');
int count = list.length;

Try this code:

class DatabaseHelper() {

  Future<List<Map<String, dynamic>>> getDataInMap() async {
      Database database = await this.database;
      return database.query("ahkam_fiqhia");
  }

  Future<List<BooksModel>> getModelsFromMapList() async {
    List<Map<String, dynamic>> mapList = await getDataInMap();

    List<DataModel> dataModel = List();

    for (int i = 0; i < mapList.length; i++) {
      dataModel(DataModel(mapList[i]));
    }
    print(mapList.length);
    return dataModel;
  }

}

Add initState() function in your view then call getModelsFromMapList function:

class _MainView extends State<MainView> {

  DatabaseHelper dbHelper = databaseHelper();  

  @override
  void initState() {
    super.initState();
    databaseHelper.getModelsFromMapList();
  }
}

This is my code using for custom column condition count

Future<int?> getCustomTaskCount(String t1) async {
Database? _database = await database;
if (_database != null) {
  var result = Sqflite.firstIntValue(await _database.rawQuery(
      'SELECT COUNT (*) FROM tableName WHERE columnName=?',
      [t1]));
  print(result);
  return result;
}}

You can use the magic column COUNT(*) as shown in the docs

Hence, the count function would look something like:

  @override
  Future<int> countUsersWithFirstName(String firstName) async {
    return Sqflite.firstIntValue(await db.query(
          'users',
          columns: ['COUNT(*)'],
          where: 'firstName = ?',
          whereArgs: [firstName],
        )) ??
        0;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM