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?
CodePudding user response:
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 e.g. :-
@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.