How to write Basic SQL commands in Room
In today’s article, I am going to present multiple different types of commands that one can use to change, retrieve and delete data inside of a traditional database. In the following I will name the most important SQL commands.
A query is a way of selecting and finding data inside of a relational database. Traditionally, queries are built with specific building blocks such as “SELECT” , “FROM” and“WHERE” but there are lots of additional query commands that can be found and used (this link may be helpful: https://www.w3schools.com/sql/sql_intro.asp). For instance, if one wants to select all professors from a given database, one could call the command:
@Query("SELECT * FROM professor_db")
To collect data from a specific column in a database one has to call the command with your respective column:
@Query("SELECT your_column FROM professor_db")
To delete entities from your database in Java, simply call
with an appropriate Entity to delete below inside an interface. If this entity doesn’t exist inside of the database or the entity is of a different kind, an exception will be thrown.
To add entities to one’s database one can use the command “Insert”. An example in Java for this would be:
@Insert(onConflict = OnConflictStrategy.REPLACE)
Below this line would be an interface that would pass an Entity to this call. What one can also depict from this code line is the parameter:
onConflict = OnConflictStrategy.REPLACE) → This ensures that if a repetition is already available to the Database with the same primary or foreign key, an exception is thrown.
To update entities in your database one can use the command “Update”. An example in Java for this would be:
To update a specific entity with an updated entity of the same kind, one can simply use the exact same interface as in the “Insert” command segment above. This action won’t affect the entire database but rather change the parameters in one’s entity. If no changes will be made the entity will stay the same, but if the entity does not exist, an exception will be thrown.