新创建的SQFlite数据库中的事务/批处理

时间:2019-07-29 11:41:40

标签: flutter sqflite

以下情况仅在代码中刚刚创建的数据库中发生。以前存在的数据库可以正常工作。

我具有数据库助手的通常的单例设置,相关部分是:

Future<Database> get database async {
  // ...
  db ??= await openDatabase(
    path.join(await getDatabasesPath(), 'database.db'),
    onCreate: (db, version) async {
      final batch = db.batch();
      batch.execute('CREATE TABLE table1 ...');
      batch.execute('CREATE TABLE table2 ...');
      await batch.commit(noResult: true);
    },
  // ...
  return db;
}

让我们假设该数据库尚不存在。我调用以下例程:

final db = await database;
await db.transaction((txn) async {
  await txn.delete('table1');
  final batch = txn.batch();
  for (data in newData1)
    batch.insert('table1', data.toJson()));
  await batch.commit(noResult: true);

  await txn.delete('table2');
  final batch = txn.batch();
  for (data in newData2)
    batch.insert('table2', data.toJson()));
  await batch.commit(noResult: true);
});

事务和批处理调用正确执行。当整个操作实际上在最后执行时,它会在第一个DELETE FROM table1 SQL操作上停止,并带有 DatabaseException(试图编写一个只读数据库(Sqlite代码1032))(在Android上运行)

我检查了单例单例,openDatabase没有被调用两次。我还尝试了exclusive: false的交易,没什么区别。

1 个答案:

答案 0 :(得分:0)

问题的可能原因是无法访问该表。这种情况的已知解决方法是打开数据库并在删除之前关闭它,如本 GitHub issue thread 中所述。