我按照本指南打开资产数据库打开资产数据库并将其复制到我的文件系统,但使用“readOnly:true”,因为我希望用户修改应用程序内的数据库。
initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "TEST.db");
var exists = await databaseExists(path);
if (!exists) {
// Should happen only the first time you launch your application
print("Creating new copy from asset");
// Make sure the parent directory exists
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
// Copy from asset
ByteData data = await rootBundle.load(join("assets", "test.db"));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Write and flush the bytes written
await File(path).writeAsBytes(bytes, flush: true);
} else {
print("Opening existing database");
}
// open the database
return await openDatabase(path, version: 1, onUpgrade: _onUpgrade);
}
这非常有效。
但后来我想修改资产数据库,例如添加新行、列或表,甚至更改特定现有列的值。当我这样做时,我想用修改后的资产数据库更新文件系统中复制的数据库。为此,我使用 onUpgrade。
_onUpgrade(Database db, int oldVersion, int newVersion) async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "TEST.db");
// Delete old database and load new asset database
await deleteDatabase(path);
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
ByteData data = await rootBundle.load(join("assets", "test.db"));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await new File(path).writeAsBytes(bytes, flush: true);
// Add new table
// Add new row or column
// Update column
}
我只知道如何在版本更改后删除文件系统中的数据库,但我不想删除用户所做的数据库中的更改。如何将新资产数据库与文件系统中的数据库合并?如何添加新表、列或行?我怎样才能更换一列?