2

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

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?

Here is a small example :


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) }
jlengrand
  • 12,152
  • 14
  • 57
  • 87

1 Answers1

2

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)

    }
}

My transactions then look like this one:

transaction(Database.connect(DB.db)) {
   SchemaUtils.createDatabase("imdb")
}
Martin Pabst
  • 861
  • 11
  • 9