Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update version database SQFLite flutter?

I need to create new tables and delete others in my local database, however changing only the database version, it does not work it is not creating the new tables that I need.

In the same way I already tried the onUpgrade but it did not work

Future<Database>  get database async{
    if( _database != null  )return _database;
    _database = await initDB();
    return _database;

  }


  initDB()async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join( documentDirectory.path, 'DB.db' );
     var ouDb =  await openDatabase(path, version: 2,onCreate: onCreate, onUpgrade: onUpgrade);
     return ouDb;
    }

  FutureOr<void> onCreate(Database db, int version) async {

      await db.execute('CREATE TABLE nameTable0...');



      db.execute("DROP TABLE IF EXISTS NameTable1");
      db.execute("DROP TABLE IF EXISTS NameTable2");



  }

  FutureOr<void> onUpgrade(Database db, int oldVersion, int newVersion) async{
      if (oldVersion < newVersion) {
        await db.execute('CREATE TABLE NameTable3 ...');
      }
      //onCreate(db, newVersion); 
  }
like image 502
Palomita Yañez Quiroz Avatar asked May 19 '20 19:05

Palomita Yañez Quiroz


1 Answers

You need to use onUpgrade

initDb() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, 'maindb.db');
    var ourDb = await openDatabase(path, version: 2, onCreate: _onCreate, onUpgrade: _onUpgrade);
    return ourDb;
  }

  // UPGRADE DATABASE TABLES
  void _onUpgrade(Database db, int oldVersion, int newVersion) {
    if (oldVersion < newVersion) {
      // you can execute drop table and create table
      db.execute("ALTER TABLE tb_name ADD COLUMN newCol TEXT;");
    }
  }
like image 200
Sanjay Sharma Avatar answered Oct 02 '22 14:10

Sanjay Sharma