Adding column in room db

Viewed 9515

I have been going through Room DB introduced in new architecture components in Android and thinking about migrating my current DBs to Room DBs.

But my current db implementation allows me to add columns to the table but as per Room, fields in POJO class represents the columns of table.

It is possible to add columns in Room DB using raw query, if yes, how shall I implement it.

2 Answers

I know this is an old post, but this might help someone out there that needs help with this.

Do you want to add said column on an upgrade of a DB or would you like to do it on first creation of the table?

If you want to do it on an upgrade of the DB then you can look at

Migrating Room databases

Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
    .addMigrations(MIGRATION_1_2, MIGRATION_2_3).build();

static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, `name` TEXT, PRIMARY KEY(`id`))");
    }
};

static final Migration MIGRATION_2_3 = new Migration(2, 3) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("ALTER TABLE Book ADD COLUMN pub_year INTEGER");
    }
};

If you want to add the column on the fly you will have to get the instance of your DB then can try call the following:

getDatabaseInstance().query()
Related