我正在嘗試遷移新的資料庫版本。唯一改變的是添加的列。我總是收到以下錯誤:
android.database.sqlite.SQLiteException: no such table: database-notes (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE 'database-notes' ADD COLUMN image TEXT
我不明白為什么會出現此例外,因為我的表被命名database-notes為 .build() 呼叫中所寫的。
這是我的資料庫類:
@Database(
version = 2,
entities = [Note::class],
exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDAO
companion object {
fun build(context: Context) = Room.databaseBuilder(context, AppDatabase::class.java, "database-notes")
.addMigrations(MIGRATION_1_2).build()
}
}
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE 'database-notes' ADD COLUMN image TEXT")
}
}
資料庫名稱與以前的版本完全相同。我復制它以排除拼寫錯誤。我在這里忽略了什么?先感謝您!
uj5u.com熱心網友回復:
因為我的表名為 database-notes
由于失敗,它似乎不是,并且可能是對資料庫名稱和表名稱之間差異的誤解。
一個資料庫可以有多個表。資料庫名稱是檔案本身的名稱(表、索引、視圖和觸發器等組件的容器)。
在您的代碼database-notes中,根據 Room.databaseBuilder 的第三個引數是資料庫(檔案)的名稱。
對于 Room,表名派生自使用 @Entity 注釋并通過 @Database 注釋的物體引數提供的類。在您的情況下是Note類。
除非您使用注釋的引數來提供另一個名稱,否則表的名稱將為Note 。tableName =@Entity
例子
如果以下是您的Note課程:-
@Entity // No tableName parameter so the table name is the class name
data class Note(
@PrimaryKey
var noteId: Long? = null,
var noteText: String,
var image: String
)
然后表名將是Note(類的名稱)
如果 Note 類是:-
@Entity(tableName = "notes") //<<<<< specifically names the table
data class Note(
@PrimaryKey
var noteId: Long? = null,
var noteText: String,
var image: String
)
表名將是注釋(由注釋的tableName =引數指定@Entity)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446745.html
