tekartik / sqflite

SQLite flutter plugin
BSD 2-Clause "Simplified" License
2.88k stars 527 forks source link

Inserting a row after clearing a table is not working #1101

Closed mhndda closed 6 months ago

mhndda commented 6 months ago

in the following code, I am trying to clear the CREDS table before adding one new row just to make sure there is only one record in the table, the queries seems to work fine (no error is showing up) but when I restart the app the data is missing, but when I remove the DELETE statement it works fine and the data shows up fine( in another function).

Code:

Future<void> dbSaveCreds({required String username, required String password}) async {
  final db = await DatabaseHelper().initDatabase();
  await db.delete('CREDS');
  final data = {'username': username, 'password': password};
  dev.log(name: 'dbSaveCreds', data.toString());
  await db.insert('CREDS', data);
}

I tried with batch and commit, still have the same result. Sorry if repeated or misleading I just couldn't find help or answer anywhere else.

alextekartik commented 6 months ago

Hard to say what is going wrong, can you confirm that data is empty after the insert (print(await db.query('CREDS)). Personnally I would do this in a transaction:

await db.transaction((txn) async {
  await txn.delete('CREDS');
  final data = {'username': username, 'password': password};
  await txn.insert('CREDS', data);
  // Tmp quick check
  print(await txn.query('CREDS'));
});
mhndda commented 6 months ago

Thank you so much, it worked now :)