I am using Sqlite database in Flutter by using sqflite plugin. Following the below mentioned links I am able to successfully create database and perform CRUD operations in it.
Sqflite Plugin
Sqflite Tutorial - Youtube Playlist
The problem is, Once the database is created I cannot modify old tables. In order to get a new column in "tabEmployee" table, I must delete the database and recreate it.
void _onCreate(Database db, int newVersion) async {
await db.execute(
"CREATE TABLE tabEmployee($idPk INTEGER PRIMARY KEY, employeeName TEXT)");
}
What should I do in order to modify previously created table in sqflite without deleting database ?
Summary. Use the ALTER TABLE statement to modify the structure of an existing table. Use ALTER TABLE table_name RENAME TO new_name statement to rename a table. Use ALTER TABLE table_name ADD COLUMN column_definition statement to add a column to a table.
SQFlite is a plugin in flutter which is used to store the data. In SQFlite we perform many operations like create, delete, update, etc. This operation is called CRUD Operations. Using this we can easily store the data in a local database.
Well I managed to resolve my issue. With some help from dlohani comment and How to add new Column to Android SQLite Database link.
I created a new method "_onUpgrade" and call it as parameter of "openDatabase" and changed the version number. Following is my relevant code:
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) {
db.execute("ALTER TABLE tabEmployee 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