我按照本指南打开了一个资产数据库,并将其复制到我的文件系统中,但使用了"readOnly:Opening an asset database“,因为我希望用户在应用程序中修改数据库。
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
}我只知道如何在版本更改后删除文件系统中的数据库,但我不想删除用户在数据库中所做的更改。如何将新资产数据库与文件系统中的数据库合并?如何添加新的表、列或行?那么如何替换列呢?
发布于 2020-04-08 00:55:49
您必须使用readOnly = false打开它。
然后,当您调用onUpgrade时,您必须运行sql查询来使用alter TABLE命令更改表。
final Future<Database> database = openDatabase(
// Set the path to the database.
join(await getDatabasesPath(), 'mydatabase.db'),
onUpgrade: (db, version ...) {
return db.execute(
"ALTER TABLE ... ADD COLUMN ...",
);
},
// Set the version to upgrade
version: 2,
);https://stackoverflow.com/questions/57621539
复制相似问题