2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Roomのcolumn追加方法

Last updated at Posted at 2019-03-23

#はじめに
覚書程度なので注意。
わかりづらいと思う。
後これがあってるかどうかもわかんない…。

#変更箇所

  • DBのVersion管理してるところ(AppDataBase)
  • DBの呼び出し箇所(Activity,Fragment)
  • DBの中身書いてるところ(Interface)

AppDatabase

DBのVersionをあげる(今回の場合は 1 → 2)

AppdataBase.kt
@Database(entities = [DBのテブル(クラス)::class], version = 2) //この部分を2へ
abstract class AppDataBase : RoomDatabase() {
    //DAOとか書いてあるけども今回は省略
}

Activity,Fragment

呼び出し部分の前に変更させるSQL文を記述

Migration.kt
val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                //カラム追加
                database.execSQL("ALTER TABLE [テーブル名] ADD [追加したいカラム名] [追加するカラムの型]")
            }
        }

呼び出し部分でMigrationを行う

Main.kt
     val dataBase =
            Room.databaseBuilder(activity.applicationContext, AppDataBase::class.java, "データベース名")
                .addMigrations(MIGRATION_1_2) //Migration
                .build()

Interface

追加したカラムのcolumnInfoを作る

InterFace.kt

@Entity
class Database {
    @PrimaryKey(autoGenerate = true)
    var userId: Int = 0

//// 追加部分
    @ColumnInfo(name = "追加したカラム名")
    var 変数名: [型]? = ""
}

#終わりに
DBを壊さずにこれで一応カラム追加とかできる。

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?