CRUD
- Kotlin course
- Advanced
- Lesson 34/83
- 5 min
Learn CRUD with insert, select, update and delete.
CRUD operations
CRUD stands for Create, Read, Update, Delete, the four basic database operations. Exposed has a function for each.
Create: Users.insert { it[name] = "Ayşe" }. Read: Users.select { Users.id eq 1 }. Update: Users.update { Users.name eq "Ayşe" where Users.id eq 1 }. Delete: Users.deleteWhere { Users.id eq 1 }. All calls live inside a transaction. Exposed generates SQL behind the scenes; you only work with the Kotlin API.
Practice Call Users.insert
Define object Users : Table() with val id = integer("id") and val name = varchar("name", 50). In main, open a connection with Database.connect, then in a transaction block call Users.insert { it[name] = "Alex" } and print println("Record added").
Starter code
// CRUD
// write here
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
fun main() {
}Sample solution
object Users : Table() {
val id = integer("id")
val name = varchar("name", 50)
}
fun main() {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
Users.insert {
it[name] = "Alex"
}
println("Record added")
}
}Expected output
Record added
select, update, deleteWhere
select reads records: Users.select { Users.id eq 1 }. update modifies records: Users.update({ Users.id eq 1 }) { it[name] = "Ayşe" }.
deleteWhere removes records: Users.deleteWhere { Users.id eq 1 }. All queries use operators like eq, lessEq, greater for conditions. select returns a Query; you can iterate rows with .forEach { row -> ... }, get the first with .first(), or collect to a list with .toList().
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which function adds a new record?
- select
- insert Correct answer
- deleteWhere
- update
Explanation: insert adds a new record.
2 Complete the deleteWhere call
Users.____ { Users.id eq 1 }
Users.deleteWhere { Users.id eq 1 }
Explanation: deleteWhere removes records.
3 Match CRUD operations
| Term | Meaning |
|---|---|
insert |
Create |
select |
Read |
update |
Update |
deleteWhere |
Delete |