Skip to content Skip to sidebar Skip to footer

Room: Using Variable In Query

I'm using Room DB in my app and I want, in a query, to put the column name as a variable so I can manipulate it 'on the go' (while calling the method). example code ('name' suppose

Solution 1:

I know this answer is quite old but since I arrived here it still can be useful.

So now you can write your queries with variables, with quite the same syntax you used. This is what the doc says:

@Query("SELECT * FROM user WHERE user_name LIKE :name AND last_name LIKE :last")
     publicabstractList<User> findUsersByNameAndLastName(String name, String last);

and

@Query("SELECT * FROM user WHERE uid IN(:userIds)")publicabstract List findByIds(int[] userIds);

Query documentation can be find here.

Solution 2:

This isn't possible in Room, or even in SQLite prepared statements in general as CommonsWare says in his comment on the original post.

Though I don't have a citation for the SQLite prepared statement feature, if you look at the Query annotation documentation for Room here, you'll see it states that "[the] query is verified at compile time ... to ensure that it compiles fine against the database.". This should be impossible with dynamic column names. You'll also notice that queries are explained with some depth, but that things like variable table, and column names are conspicuously missing.

Solution 3:

I know this is a bit late but maybe it would be useful for others. instead of using @Query annotation in dao you could try using @RawQuery which accepts SupportSQLiteQuery as value then write your query in old fashioned way

Post a Comment for "Room: Using Variable In Query"