'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);
}
Solution 1:[1]
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;");
}
}
Solution 2:[2]
I think it will help you...
Future<Database> openDatabase(String path,
int version,
{OnDatabaseConfigureFn? onConfigure,
OnDatabaseCreateFn? onCreate,
OnDatabaseVersionChangeFn? onUpgrade,
OnDatabaseVersionChangeFn? onDowngrade,
OnDatabaseOpenFn? onOpen,
bool readOnly = false,
bool singleInstance = true}) {
final options = OpenDatabaseOptions(
version: 4,
onConfigure: onConfigure,
onCreate: _createDb,
onUpgrade: _upgradeDb,
onDowngrade: onDowngrade,
onOpen: onOpen,
readOnly: readOnly,
singleInstance: singleInstance);
return databaseFactory.openDatabase(path, options: options);
}
Call it any where in your code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sanjay Sharma |
| Solution 2 | Rahul Kumar |
