简体   繁体   中英

Android room inserting with a query

I know inserting data into SQlite room library can be done through @Insert annotation, but I (out of curiosity) tried inserting values through SQL statement but Android studio showed me error stating column names can't be resolved. Is it a way of forcing developer to use @Insert annotation or if I am doing something wrong here? Thanks!

Please review following screenshot - 在此处输入图片说明

If you omit the column list that is being highlighted and thus provide values for all columns eg :-

@Query("INSERT INTO TestTable VALUES(null,:a,:b)")
List<TestTable> getall(String a, String b, String columna, String columnb);

Android Studio doesn't complain but then you get a compiler error of :-

error: INSERT query type is not supported yet. You can use:SELECT, DELETE, UPDATE

So perhaps better sooner than later.

What I am doing is calling getOpenHelper().getWritableDatabase() on the RoomDatabase .

Then you get the SupportSQLiteDatabase object that is essentially the non-Room way.

From that you can call execSQL() or use insert() with table name and ContentValues .

@Entity
data class ModulesRoom(
    @PrimaryKey(autoGenerate = false)
    var id: Int = 0,
    var nav: String = "",
    var name: String = "",
    var imageurl: String = ""
)
for List Object
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveEmployees(modules: List<ModulesRoom>)

for single obbjet
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveEmployees(modules: ModulesRoom)

Ussage 
val mModules = Modules() 
mModules.id = values
mModules.nav = values 
saveEmployees(mModules)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM