简体   繁体   中英

How to get specific column from android room db?

I tried to get columns through column names in DAO, but it didn't work.

@Query("SELECT :columnName FROM info_table")
suspend fun getItem(columnName: String): List<Any>

I have so many columns so It is not proper approach.

@Query("SELECT TIME FROM info_table")
suspend fun getTime(): List<Long>

So How can i deal with it?

Unless you hard code the column names you cannot use a variable for the column name in an @Query annotation.

However, you could utilise a RawQuery eg :-

@RawQuery
fun rawQuery(theQuery: SimpleSQLiteQuery): List<String>
fun getAColumnFromATable(columnName: String, tableName: String): List<String> {
     return rawQuery(SimpleSQLiteQuery("SELECT $columnName FROM $tableName"))
}
  • in which case you use the getAColumnFromATable function, which in this case would return a List which would be capable of getting any values store in the database with the exception of ByteArrays (BLOBS in SQLite terms, in which case you could utilise the SQLite built-in hex function).

  • this is more than you asked for as it has the additional flexibility of being able to work for any table.

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