KatchS
KatchS

Reputation: 101

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 to be a variable represent a column):

@Query("UPDATE Products SET :name = :value WHERE prod_id = :prod_id")
    int updateName(String name,String value, String prod_id);

I tried that but it does not compile, with an error that it needs to get a column and not a String.

Is there any way that even a column will be placed as a variable?

Upvotes: 8

Views: 7874

Answers (3)

Dan Chaltiel
Dan Chaltiel

Reputation: 8484

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")
     public abstract List<User> findUsersByNameAndLastName(String name, String last);

and

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

Query documentation can be find here.

Upvotes: 5

alireza rahmaty
alireza rahmaty

Reputation: 596

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

Upvotes: 0

M.Pomeroy
M.Pomeroy

Reputation: 1126

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.

Upvotes: 3

Related Questions