Skip to main content
Kotlin Basics
CHAPTER 25 Beginner

Kotlin Database Programming

Updated: May 18, 2026
5 min read

# CHAPTER 25

Kotlin Database Programming

1. Chapter Introduction

When building an app like a To-Do list, saving data to a simple text file is inefficient when searching or sorting. Applications require Relational Databases. Android devices come with a built-in lightweight database called SQLite. However, writing raw SQL queries as strings is prone to crashing if you misspell a column name. To solve this, Google created the Room Persistence Library, which maps Kotlin Data Classes directly to SQLite tables securely!

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the role of SQLite in mobile apps.
  • Understand the Room architecture (Entity, DAO, Database).
  • Define a database table using @Entity.
  • Define database operations using a @Dao.
  • Execute CRUD (Create, Read, Update, Delete) operations.

3. The Room Architecture

Room has three main components:
  1. 1. Entity: A Kotlin Data Class representing a single table in the database.
  1. 2. DAO (Data Access Object): An Interface containing the SQL methods to access the database.
  1. 3. Database: An abstract class that ties the Entities and DAOs together to create the actual database instance.

4. Step 1: The Entity (The Table)

We use Annotations (like @Entity and @PrimaryKey) to tell Room how to convert our Kotlin data class into an SQLite table.
kotlin
12345678910111213
import androidx.room.Entity
import androidx.room.PrimaryKey

// This creates a table named "students"
@Entity(tableName = "students")
data class Student(
    // AutoGenerate means SQLite will automatically create 1, 2, 3...
    @PrimaryKey(autoGenerate = true) 
    val id: Int = 0,
    
    val name: String,
    val grade: String
)

5. Step 2: The DAO (The Queries)

The DAO is an Interface. We write the method signatures and attach SQL queries to them using annotations. Room writes the actual messy implementation code for us!

*Crucial: Database queries are slow. We MUST mark them as suspend functions so they run safely inside Coroutines!*

kotlin
1234567891011121314151617
import androidx.room.*

@Dao
interface StudentDao {
    
    // Insert a new student
    @Insert
    suspend fun insertStudent(student: Student)
    
    // Get all students
    @Query("SELECT * FROM students ORDER BY name ASC")
    suspend fun getAllStudents(): List<Student>
    
    // Delete a student
    @Delete
    suspend fun deleteStudent(student: Student)
}

6. Step 3: The Database

We create an abstract class that extends RoomDatabase. We define which Entities exist and which DAOs can be used.
kotlin
12345678910
import androidx.room.Database
import androidx.room.RoomDatabase

// Set version=1. If we change the table structure later, we must increase this version.
@Database(entities = [Student::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    
    // Expose the DAO
    abstract fun studentDao(): StudentDao
}

7. Executing Database Operations

To actually save data, we use Coroutines (lifecycleScope or viewModelScope in Android) to call our suspend DAO methods without freezing the UI.
kotlin
12345678910
// Example inside an Android Activity/ViewModel
fun saveStudent(db: AppDatabase, name: String, grade: String) {
    val newStudent = Student(name = name, grade = grade)
    
    // Launch a background coroutine!
    GlobalScope.launch {
        db.studentDao().insertStudent(newStudent)
        println("Student saved successfully!")
    }
}

8. Common Mistakes

  • Running Queries on the Main Thread: Room actively prevents this. If you try to call .insertStudent() without a Coroutine, Room will crash the app with a Cannot access database on the main thread exception to protect the UI.
  • Forgetting @PrimaryKey: Every SQLite table must have a primary key to uniquely identify rows. Room will refuse to compile if your Entity is missing one.

9. Best Practices

  • Use the Repository Pattern: Don't call the database directly from your UI (Activity/Fragment). Create a Repository class that handles the database calls, and have the UI communicate with the Repository.

10. Exercises

*(Theoretical)*
  1. 1. Define a @Entity data class for a Book with properties id, title, and author.
  1. 2. Define a @Dao interface with an @Insert function for the Book.

11. MCQs with Answers

Question 1

What is the built-in database system provided by Android?

Question 2

What Google library provides an abstraction layer over SQLite to make database access safer and easier?

Question 3

In Room, what annotation is used to turn a data class into a database table?

Question 4

What annotation ensures a specific variable is used as the unique identifier for a database row?

Question 5

What does DAO stand for?

Question 6

Where do you define your SQL queries (like @Query("SELECT * FROM users")) in Room?

Question 7

Why must database insert/read operations be marked as suspend functions?

Question 8

What happens if you attempt to run a Room database query on the Main UI Thread?

Question 9

What keyword tells Room to automatically generate incrementing numbers (1, 2, 3) for IDs?

Question 10

What defines the overall database holder and serves as the main access point for the underlying SQLite connection?

12. Interview Questions

  • Q: Explain the three primary components of the Room Database architecture.
  • Q: Why does Room heavily utilize Kotlin Coroutines? (Answer: Because database I/O is a blocking operation. Coroutines allow the queries to run asynchronously, ensuring smooth 60fps UI rendering).

13. Summary

Storing structured data locally is a requirement for almost all production apps. The Room library elegantly bridges the gap between Object-Oriented Kotlin and Relational SQLite. By using Annotations to define Entities and DAOs, Room generates thousands of lines of boilerplate code and provides compile-time verification for SQL queries, making database crashes a thing of the past.

14. Next Chapter Recommendation

Local data is great, but what if you want to display the current weather or a feed of social media posts? In Chapter 26: REST APIs and JSON Handling, we will learn how to connect our applications to the internet and parse JSON data.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·