Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 613
KatchS Avatar asked Dec 19 '17 19:12

KatchS


People also ask

What is DAO Room?

In Room, Data Access Objects or DAOs are used to access your application's persisted data. They are a better and modular way to access your database as compared to query builders or direct queries. A DAO can be either an interface or an abstract class.

What is DAO in android?

Data Access Objects are the main classes where you define your database interactions. They can include a variety of query methods. The class marked with @Dao should either be an interface or an abstract class. At compile time, Room will generate an implementation of this class when it is referenced by a Database .


2 Answers

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.

like image 115
Dan Chaltiel Avatar answered Oct 10 '22 21:10

Dan Chaltiel


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.

like image 23
M.Pomeroy Avatar answered Oct 10 '22 22:10

M.Pomeroy