我需要为现有表的当前数据库添加新的列名id INTEGER AUTOINCREMENT
和新表。如何使用“onUpgrade”?是否需要更改版本号?
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "HelperDatabase.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate, onUpgrade: _onUpgrade);
return theDb;
}
如何使用
_onUpgrade
void _onUpgrade(Database db, int oldVersion, int newVersion)async{
}
是否还需要添加列?
void _onCreate(Database db, int version) async {
await db.execute(
"""CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");
最佳答案
要从旧版本更新数据库,应将version
更改为2
。
您应该像下面那样更改onCreate
和onUpdate
。
// This is called for new users who have no old db
void _onCreate(Database db, int version) async {
// if `AssetAssemblyTable` has a new column in version 2, add the column here.
await db.execute(
"""CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");
)
await db.execute("CREATE TABLE NewTable...") // create new Table
}
// This is called for existing users who have old db(version 1)
void _onUpgrade(Database db, int oldVersion, int newVersion)async{
// In this case, oldVersion is 1, newVersion is 2
if (oldVersion == 1) {
await db.execute("ALTER TABLE AssetAssemblyTable...") // add new column to existing table.
await db.execute("CREATE TABLE NewTable...") // create new Table
}
}
下面是更多示例
https://github.com/tekartik/sqflite/blob/master/sqflite/doc/migration_example.md
关于dart - 如何将新表添加到sqlite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56248737/