KotlinΒΆ
Use JDBC to connect to CrateDB from Kotlin applications.
About
JDBC is a standard Java API that provides a common interface for accessing databases in Java.
Driver options
Like when using Java, you have two JDBC driver options:
The PostgreSQL JDBC Driver and the CrateDB JDBC Driver.
PostgreSQL JDBC uses the jdbc:postgresql:// protocol identifier,
while CrateDB JDBC uses jdbc:crate://.
Synopsis
example.kt
import java.sql.DriverManager
import java.util.*
fun main() {
// Connect to database.
val jdbcUrl = "jdbc:postgresql://localhost:5432/doc?sslmode=disable"
// val jdbcUrl = "jdbc:crate://localhost:5432/doc?sslmode=disable"
val connection = DriverManager.getConnection(jdbcUrl, "crate", "crate")
// Invoke query.
val query = connection.prepareStatement("SELECT * FROM sys.summits ORDER BY height DESC LIMIT 3")
val result = query.executeQuery()
// Display results.
while (result.next()) {
val mountain = result.getString("mountain")
val height = result.getInt("height")
println("${mountain}: ${height}")
}
}
build.gradle.kts
plugins {
java
kotlin("jvm") version "2.2.20"
application
}
repositories {
mavenCentral()
}
dependencies {
runtimeOnly("org.postgresql:postgresql:42.7.8")
// runtimeOnly("io.crate:crate-jdbc:2.7.0")
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(11))
}
}
application {
mainClass = "ExampleKt"
}
kotlin {
sourceSets.main {
kotlin.srcDir(".")
}
}
Start CrateDB using Docker or Podman, then invoke the example program.
docker run --rm --publish=5432:5432 docker.io/crate '-Cdiscovery.type=single-node'
gradle run
SSL connection
Use the sslmode=require parameter, and replace username, password,
and hostname with values matching your environment.
Also use this variant to connect to CrateDB Cloud.
val jdbcUrl = "jdbc:postgresql://testcluster.cratedb.net:5432/doc?sslmode=require"
// val jdbcUrl = "jdbc:crate://testcluster.cratedb.net:5432/doc?sslmode=require"
val connection = DriverManager.getConnection(jdbcUrl, "admin", "password")