Working with Databases

Learn how to connect to a database in the Vert.x application using Kotlin language.

To be able to progress further with our tests, we need the ability to create entities in the database. For that, we’ll need to connect to the database.

First, let’s add the following two lines to our build.gradle.kts dependencies section:

implementation("org.postgresql:postgresql:42.3.0")
implementation("io.vertx:vertx-pg-client:$vertxVersion")

The first line of code fetches the PostgreSQL driver. The second one adds the Vert.x JDBC client, which allows Vert.x, which has the driver, to connect to any database that supports JDBC.

Managing configuration

Now, we want to hold the database configuration somewhere. For local development, it may be fine to have those configurations hardcoded. We’ll execute the following steps to do this:

  1. When we connect to the database, we need to specify the following parameters at the very least:
  • Username
  • Password
  • Host
  • Database name

We’ll store the preceding parameters in a Singleton object:

object Db {
 val username = System.getenv("DATABASE_USERNAME")
     ?: "cats_admin"
 val password = System.getenv("DATABASE_PASSWORD")
     ?: "abcd1234"
 val database = System.getenv("DATABASE_NAME")
     ?: "cats_db"
 val host = System.getenv("DATABASE_HOST")
     ?:
...