Summary - Exposed SQL
- Kotlin course
- Advanced
- Lesson 36/83
- 5 min
Combine Table, transaction and CRUD to write a user database.
Summary - Exposed SQL
This group covered Exposed, Table, transaction, CRUD and join. They are the foundations of SQL database work in Kotlin.
You open a Database.connect, declare a table with object : Table(), wrap work in a transaction, do CRUD with insert/select/update/deleteWhere, and combine tables with innerJoin. Together they form a type safe data access layer.
Practice Summary: Table and insert
Define object Users : Table() with val id = integer("id") and val name = varchar("name", 50). In main, open Database.connect, in a transaction block call Users.insert { it[name] = "Alex" } and print println("Summary ready").
Starter code
// Summary: Exposed
// 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("Summary ready")
}
}Expected output
Summary ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is used to remove a record?
- select
- insert
- update
- deleteWhere Correct answer
Explanation: deleteWhere removes records.
2 Match all Exposed concepts
| Term | Meaning |
|---|---|
Database.connect |
Connection |
Table |
Table |
transaction |
Transaction |
insert |
Insert |
innerJoin |
Join |