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);
}
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;");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With