PostgreSQL JDBC

Java: JDBC, QA

Connect to CrateDB using PostgreSQL JDBC.

About

The PostgreSQL JDBC Driver is an open-source JDBC driver written in Pure Java (Type 4), which communicates using the PostgreSQL native network protocol. PostgreSQL JDBC needs Java >= 8.

Synopsis

example.java

import java.sql.*;

void main() throws SQLException {

    // Connect to database.
    Properties properties = new Properties();
    properties.put("user", "crate");
    properties.put("password", "crate");
    Connection conn = DriverManager.getConnection(
        "jdbc:postgresql://localhost:5432/?sslmode=disable",
        properties
    );
    conn.setAutoCommit(true);

    // Invoke query.
    Statement st = conn.createStatement();
    st.execute("SELECT mountain, height FROM sys.summits ORDER BY height DESC LIMIT 5;");

    // Display results.
    ResultSet rs = st.getResultSet();
    while (rs.next()) {
        System.out.printf(Locale.ENGLISH, "%s: %d\n", rs.getString(1), rs.getInt(2));
    }
    conn.close();

}

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.

properties.put("user", "admin");
properties.put("password", "password");
Connection conn = DriverManager.getConnection(
    "jdbc:postgresql://testcluster.cratedb.net:5432/?sslmode=require",
    properties
);

Install

Download

Navigate to the PostgreSQL JDBC Driver installation page.

https://jdbc.postgresql.org/download/

Directly download the recommended postgresql-42.7.8.jar.

https://repo1.maven.org/maven2/org/postgresql/postgresql/42.7.8/postgresql-42.7.8.jar
Linux / macOS
wget https://repo1.maven.org/maven2/org/postgresql/postgresql/42.7.8/postgresql-42.7.8.jar
Windows
Invoke-WebRequest https://repo1.maven.org/maven2/org/postgresql/postgresql/42.7.8/postgresql-42.7.8.jar -OutFile postgresql-42.7.8.jar

Maven pom.xml

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.7.8</version>
</dependency>

Gradle build.gradle

repositories {
    mavenCentral()
}
dependencies {
    implementation 'org.postgresql:postgresql:42.7.8'
}

Run

Quickstart example

Create the file example.java 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'

Invoke program. This example needs Java >= 25 (JEP 512), with earlier versions please use the full example.

java -cp postgresql-42.7.8.jar example.java

Full example

Connect to CrateDB using JDBC.

https://github.com/crate/cratedb-examples/tree/main/by-language/java-jdbc