Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room Fetch data with dynamic table name

Is it possible to fetch data by passing the table name as a parameter? Something like this.

@Query("SELECT id, name from :tableName")
fun getData(tableName: String): List<RandomModel>
like image 534
Sujin Shrestha Avatar asked May 29 '26 00:05

Sujin Shrestha


2 Answers

Try this

@Dao
interface RawDao {
 @RawQuery
 List<RandomModel> getData(SupportSQLiteQuery query);
}

 SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM "+ tablename);
 List<RandomModel> models = rawDao.getUserViaQuery(query);
like image 66
sadat Avatar answered May 30 '26 15:05

sadat


I think Room does not support dynamic tableName.

We have two ways:

1-In DAO, we can replace tableName with the actual table name, as defined on the model @Entity

2-We can use @RawQuery like this :

@Dao
 interface RawDao {
     @RawQuery
     User getUserViaQuery(SupportSQLiteQuery query);
 }
 SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM User WHERE id = ? LIMIT 1",
         new Object[]{userId});
 User user2 = rawDao.getUserViaQuery(query);

You can study more at this

like image 42
milad salimi Avatar answered May 30 '26 13:05

milad salimi