Create a table with Exposed
Exposed - A Kotlin SQL Library
Exposed is a prototype for a lightweight SQL library written over JDBC driver for Kotlin language.
Complete code snippet of these step’s code given at the end of this story and to read in detail about exposed, here is the link: Exposed
Follow given below steps to get the database connection and create a table schema.
- Add Exposed dependency to your project’s app module build.gradle file.
//Database dependencies
compile 'org.jetbrains.exposed:exposed:0.11.2'
2. Get a database connection with the given below code where I am using PostgreSQL dialect for the database.
val db = Database.connect(
"jdbc:postgresql://localhost:5432/databasename", driver = "org.postgresql.Driver",
user = "postgres", password = "dbpass"
)
3. Create User.kt file and which will be used as DAO(data access object). This DAO class will contain the column's name and their properties.
object Users : Table() {
val id = integer("id").autoIncrement().primaryKey()
val fullName = varchar("fullname", 50)
val userName = varchar("username", 50)
val password = varchar("keypass", 30)
val email = varchar("email", 80)
}
4. Create a Transaction block because all CRUD operations in Exposed must be called from within a transaction.
//Create user table
SchemaUtils.create(Users)
5. Full code snippet for getting the database connection and creating User table schema here:
fun main(args: Array<String>): Unit {
io.ktor.server.netty.EngineMain.main(args)
val db = Database.connect(
"jdbc:postgresql://localhost:5432/databasename", driver = "org.postgresql.Driver",
user = "postgres", password = "dbpass"
)
transaction {
//Create user table
SchemaUtils.create(Users)
}
}
Thanks for reading this story. I’ll be happy to help if you have any questions or need any help on Exposed — Kotlin’s SQL library.
Let’s make a happily coding journey with a clap. :-)