Scala¶
Connect to CrateDB from Scala applications using JDBC.
About
Driver options
Choose one of two JDBC drivers:
PostgreSQL JDBC —
jdbc:postgresql://CrateDB JDBC —
jdbc:crate://
Prefer the PostgreSQL JDBC driver first, it is often already in your classpath and works out of the box. If your application or framework emits PostgreSQL‑specific SQL that CrateDB doesn’t support, switch to the CrateDB JDBC driver for full CrateDB dialect support and smoother integration.
For example, the JDBC catalog integration with Apache Flink depends on CrateDB JDBC, in this case we recommend to use that driver depending on your needs.
The CrateDB JDBC internals page includes more information about compatibility and differences between the two driver variants, and more details about the CrateDB JDBC Driver.
Synopsis
build.sbt
scalaVersion := "3.3.7"
libraryDependencies ++= Seq(
"org.postgresql" % "postgresql" % "42.7.8",
)
example.scala
import java.sql.{Connection, DriverManager, ResultSet}
import scala.util.Using
object Example {
def main(args: Array[String]): Unit = {
// Configure connection.
val driver = "org.postgresql.Driver"
val url = "jdbc:postgresql://localhost:5432/?sslmode=disable"
val username = "crate"
val password = "crate"
// Connect to the database.
Class.forName(driver)
try {
Using.resource(DriverManager.getConnection(url, username, password)) { connection =>
// Run a basic query.
val statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
val resultSet = statement.executeQuery("SELECT mountain, height FROM sys.summits ORDER BY height DESC LIMIT 5")
// Display results.
while (resultSet.next()) {
val mountain = resultSet.getString("mountain")
val height = resultSet.getInt("height")
println(mountain + ": " + height)
}
}
} catch {
case e: Exception => e.printStackTrace()
}
}
}
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 url = "jdbc:postgresql://testcluster.cratedb.net:5432/?sslmode=require"
val username = "admin"
val password = "password"
Quickstart example
Create the files build.sbt and example.scala including the synopsis code shared above.
Start CrateDB using Docker or Podman, then invoke the example program.
docker run --rm --publish=5432:5432 docker.io/crate '-Cdiscovery.type=single-node'
sbt run