Как добавить новую таблицу в sqlite? - PullRequest
0 голосов
/ 22 мая 2019

Мне нужно добавить имя нового столбца 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)""");

1 Ответ

0 голосов
/ 22 мая 2019

Чтобы обновить вашу БД со старой версии, вы должны изменить 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

...