0

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?

goodies
  • 11
  • 2

1 Answers1

0

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.

MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Thanks a lot, It works well by the way, when I got data into List type, It didn't. I miss we always declare the type of data. – goodies Sep 20 '22 at 04:25
  • @goodies List cannot be the case. Any object other than types based upon integer, String or decimal would not work. Data can only be stored in the database as those types (and the mentioned BLOB). Any, bar the BLOB, can be returned as a String automatically. Hence the List. With numeric types, the result could be unpredictable *(e.g. what is the numeric value of Z?)* Whilst Z, 1, 1.1111111 can all be represented by a String. If the answer helped you then please consider ticking it as answered. This then indicates to others that the answer was useful. – MikeT Sep 20 '22 at 06:10
  • Yes, you're right. it is always possible when String type. and i have one more question, I changed my databases from SQLite to Room. and when i used SQLite, String type was really slow to get data. Is that also slow when getting data in Room databases? – goodies Sep 20 '22 at 07:51
  • @goodies little difference. Room is just a wrapper around SQLite, so underneath it exactly the same BUT there will be some overheads with room. An example being that when opening the database with Room it checks a compiled hash against a has stored in room_master_table to see is the schema has changed. – MikeT Sep 20 '22 at 08:28