Privacy of Animal
Privacy of Animal

Reputation: 451

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

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?

Upvotes: 4

Views: 11005

Answers (4)

Abbas Jafari
Abbas Jafari

Reputation: 1643

I know it's too late, but here is a simple solution for other people:

  Future<YourModel> checkValue(key) async {
    List<Map> maps = await db.query(your_table_name,
        columns: [
          columnId,
          columnKey,
          columnTitle,
        ],
        where: '$columnKey = ?',
        whereArgs: [key]);
    if (maps.length > 0) {
      return MainItem.fromMap(maps.first);
    }
    return null;
  }

And to use this method:

bool isExist = checkValue("your_key") != null;

Upvotes: 0

Andrei Erdoss
Andrei Erdoss

Reputation: 1643

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;
}

Upvotes: 2

moshire
moshire

Reputation: 111

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;
      }

Upvotes: 6

Salma
Salma

Reputation: 1280

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

Upvotes: 8

Related Questions