2

我需要id INTEGER AUTOINCREMENT为现有表的当前数据库添加一个新列名和一个新表。如何使用“升级”?是否需要更改版本号?

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)""");
4

1 回答 1

3

要从旧版本更新您的数据库,您应该更改version2. 你应该改变onCreateonUpdate如下所示。

// 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

于 2019-05-22T10:30:37.233 回答