GroovyΒΆ

Use JDBC to connect to CrateDB from Groovy 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.groovy

import groovy.sql.Sql

class Example {

    static void main(String[] args) {

        // Configure database.
        Map dbConnParams = [
          url: 'jdbc:postgresql://localhost:5432/doc?sslmode=disable',
          // url: 'jdbc:crate://localhost:5432/doc?sslmode=disable',
          user: 'crate',
          password: 'crate',
        ]

        // Connect to database, invoke query, and display results.
        Sql.withInstance(dbConnParams) { sql ->
            sql.eachRow("SELECT region, mountain, height FROM sys.summits ORDER BY height DESC LIMIT 3") { rs ->
                println rs
            }
        }
    }

}

build.gradle

plugins {
    id 'groovy'
    id 'application'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.codehaus.groovy:groovy-all:3.0.25'
    runtimeOnly 'org.postgresql:postgresql:42.7.8'
    // runtimeOnly 'io.crate:crate-jdbc:2.7.0'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(11)
    }
}

application {
    mainClass = 'Example'
}

sourceSets {
    main.groovy.srcDirs = ['.']
}

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.

Map dbConnParams = [
  url: 'jdbc:postgresql://testcluster.cratedb.net:5432/doc?sslmode=require',
  // url: 'jdbc:crate://testcluster.cratedb.net:5432/doc?sslmode=require',
  user: 'admin',
  password: 'password',
]