Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room: how to check whether row exists

Tags:

In my repository class, I want to fetch data only if none exists in a Room table. How to check whether any row exists in a table?

like image 831
Jack Guo Avatar asked Jul 02 '18 15:07

Jack Guo


People also ask

How do you check data is exist or not in room database?

For check data exists or not you can get int value. @Query("SELECT * FROM TableName WHERE userName = :userName") int isDataExist(String userName); call this query using below code.

What is Dao in room?

When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.

What does a room query return if nothing is found?

If nothing is found based on your criteria, it will return null.

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.


2 Answers

You can use EXISTS operator and return just Boolean:

@Query("SELECT EXISTS(SELECT * FROM table)")
fun hasItem(): Boolean
like image 40
Maxim Pestryakov Avatar answered Sep 17 '22 18:09

Maxim Pestryakov


Use EXISTS operator, and return 1 means true and 0 means false.

If you want to check some specific row and some condition, do this trick:

@Query("SELECT EXISTS(SELECT * FROM tableName WHERE id = :id)")
fun isRowIsExist(id : Int) : Boolean

Or simple use this:

@Query("SELECT EXISTS(SELECT * FROM tableName)")
fun isExists(): Boolean
like image 77
Tarif Chakder Avatar answered Sep 21 '22 18:09

Tarif Chakder