在Kotlin中操作数据库:PostgreSQL与MongoDB实战

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

引言:为什么Kotlin是操作数据库的绝佳选择

Kotlin作为一种现代且简洁的编程语言,为开发者提供了与各种数据库交互的强大工具。凭借与Java的完全兼容性以及自身的库生态系统,Kotlin能够编写安全、富有表现力且高性能的代码,用于操作关系型(SQL)和文档型(NoSQL)存储。

在本文中,我们将通过实际示例,讲解如何连接并执行两种流行数据库管理系统(PostgreSQL(关系型)和MongoDB(文档型))的CRUD操作(创建、读取、更新、删除)。您将学习如何配置项目、使用现代库(用于SQL的Exposed和用于MongoDB的KMongo),并根据Kotlin的特性编写简洁的代码。



1. 在Kotlin中操作PostgreSQL:使用Exposed库

在Kotlin中操作关系型数据库有多种方法。我们将介绍Exposed库——一个用Kotlin编写的轻量级ORM封装,它提供了类型安全的DSL(领域特定语言)来构建SQL查询。



1.1. 添加依赖

在build.gradle.kts文件中添加以下依赖:

dependencies {    implementation("org.jetbrains.exposed:exposed-core:0.41.1")    implementation("org.jetbrains.exposed:exposed-dao:0.41.1")    implementation("org.jetbrains.exposed:exposed-jdbc:0.41.1")    implementation("org.postgresql:postgresql:42.6.0")    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")}


1.2. 创建表并连接数据库

在代码中定义"用户"实体及其对应的表:

import org.jetbrains.exposed.sql.*import org.jetbrains.exposed.sql.transactions.transactionimport org.jetbrains.exposed.sql.SqlExpressionBuilder.eq

// 定义表object Users : Table() { val id = integer("id").autoIncrement() val name = varchar("name", 255) val email = varchar("email", 255).uniqueIndex()

override val primaryKey = PrimaryKey(id)}

// 用户的数据类data class User(val id: Int, val name: String, val email: String)

fun main() { // 连接数据库 Database.connect( url = "jdbc:postgresql://localhost:5432/mydb", driver = "org.postgresql.Driver", user = "postgres", password = "password" )

// 创建表(如果不存在) transaction { SchemaUtils.create(Users) }}


1.3. CRUD操作

现在实现基本的创建、读取、更新和删除记录操作:

fun createUser(name: String, email: String): User {    return transaction {        val insertId = Users.insert {            it[Users.name] = name            it[Users.email] = email        } get Users.id

User( id = insertId, name = name, email = email ) }}

fun readUserById(id: Int): User? { return transaction { Users.selectAll().where { Users.id eq id } .singleOrNull() ?.let { row -> User( id = row[Users.id], name = row[Users.name], email = row[Users.email] ) } }}

fun updateUserEmail(id: Int, newEmail: String) { transaction { Users.update({ Users.id eq id }) { it[email] = newEmail } }}

fun deleteUser(id: Int) { transaction { Users.deleteWhere { Users.id eq id } }}

借助Exposed,Kotlin代码变得简洁且类型安全。列名或表名的错误可以在编译时捕获。

博客

书籍推荐