How can I know if row is exist in flutter sqflite?

6,937

Solution 1

I'm assuming you want to check if there's a record that exists with the specified criteria in the database and do something if it does exist.

getting the result from the database and storing in a queryResult: var queryResult = await db.rawQuery('SELECT * FROM tagTable WHERE uidCol="aaa"');

checking if the result is empty:

 result.isNotEmpty ? //do something if the result is not empty here
 : []; //else return empty list

Solution 2

Try this it worked for me

var db= DatabaseHelper();

Future<int> getcount(id) async {
      var dbclient = await db;
      int  count = Sqflite.firstIntValue(
          await dbclient.rawQuery("SELECT COUNT(*) FROM $cartTable WHERE $columnid=$id"));
      return count;
      }

Solution 3

You could check if any records exist using EXISTS

Future<bool> uidExists() async {
  var result = await _database.rawQuery(
    'SELECT EXISTS(SELECT 1 FROM tagTable WHERE uidCol="aaa")',
  );
  int exists = Sqflite.firstIntValue(result);
  return exists == 1;
}
Share:
6,937
Privacy of Animal
Author by

Privacy of Animal

Updated on December 09, 2022

Comments

  • Privacy of Animal
    Privacy of Animal over 1 year

    I have to know a specific row is exist where uidCol column is aaa in tagtable. But I didn't know so I'm just using try~catch block.

    What I want to do is to check local DB and if there are no data, fetching from firestore.

    What I'm doing is like below

    try {
      await db.rawQuery('SELECT * FROM tagTable WHERE uidCol="aaa"');
    } catch(exception){
      await _fetchTagsFromFirestore().catchError((e){
        print('FATAL ERROR: ${e.toString()}');
        return FETCH_RESULT.FAILURE;
      });
    }
    

    But I think it is not right way to check row is exist. How can I deal with properly?