使用Kotlin Exposed创建数据库后连接到数据库 [英] Connecting to a database after creating it with Kotlin Exposed

查看:138
本文介绍了使用Kotlin Exposed创建数据库后连接到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jetbrains公开的库来创建和填充数据库.

I'm using jetbrains' exposed library to create and populate a database.

该数据库不存在,我正在创建它.但是,我找不到简单的方法来连接到SQL引擎,创建数据库并在没有多个连接的情况下连接到该数据库.听起来有点笨拙.也许有更好的方法吗?

The database does not exist, and I am creating it. However I could not find a simple way to connect to the SQL engine, create a database and connect to that database without multiple connections. That sounds a little clunky. Is there a better way to do it maybe?

这是一个小例子:


var db = Database.connect("jdbc:mysql://localhost:3308", driver = "com.mysql.jdbc.Driver", user = "root", password = "aRootPassword")

transaction(db) { SchemaUtils.createDatabase("imdb") }

// avoid reconnect?
db = Database.connect("jdbc:mysql://localhost:3308/imdb", driver = "com.mysql.jdbc.Driver", user = "root", password = "aRootPassword")

transaction(db) { SchemaUtils.create (TitleRatings) }

推荐答案

您需要一个连接池,例如 HikariCP .它合并数据库连接并重用它们.与单独打开的连接相比,这可以极大地提高性能.

You need a connection pool, e.g. HikariCP. It pools database connections and reuses them. This gives you a huge performance boost compared to individually opened connections.

我通常将其包装在一个简单的类中,如下所示:

I usually wrap it in a simple class like this:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import javax.sql.DataSource

public object DB {

    var db: DataSource = connect();

    public fun connect(): DataSource {
        val config = HikariConfig()
        config.jdbcUrl = "jdbc:mysql://localhost:3308"
        config.username = "com.mysql.jdbc.Driver"
        config.password = "aRootPassword"
        config.driverClassName = "com.mysql.jdbc.Driver"

        return HikariDataSource(config)

    }
}

然后我的交易如下:

transaction(Database.connect(DB.db)) {
   SchemaUtils.createDatabase("imdb")
}

这篇关于使用Kotlin Exposed创建数据库后连接到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆