MotherDuck Now Speaks Postgres! Our pg_endpoint is now live!Demo - April 21

Skip to main content

Connect from Java via Postgres endpoint

Preview
This feature is in preview and is subject to change.

You can query MotherDuck from Java using the standard PostgreSQL JDBC driver — no DuckDB installation required.

For connection parameters, SSL options, and limitations, see the Postgres Endpoint reference.

Prerequisites

You'll need a MotherDuck access token. Set it as an environment variable:

export MOTHERDUCK_TOKEN="your_token_here"

Add the PostgreSQL JDBC driver to your project:

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

Connect

import java.sql.*;

public class MotherDuckExample {
public static void main(String[] args) throws SQLException {
String token = System.getenv("MOTHERDUCK_TOKEN");
String url = "jdbc:postgresql://pg.us-east-1-aws.motherduck.com:5432/md:"
+ "?sslmode=verify-full"
+ "&sslfactory=org.postgresql.ssl.DefaultJavaSSLFactory";

try (Connection conn = DriverManager.getConnection(url, "postgres", token);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT title, score FROM sample_data.hn.hacker_news WHERE type='story' LIMIT 10")) {

ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();

while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
System.out.print(meta.getColumnName(i) + "=" + rs.getString(i));
if (i < columnCount) System.out.print(", ");
}
System.out.println();
}
}
}
}

You can also configure the connection using a Properties object:

import java.sql.*;
import java.util.Properties;

Properties props = new Properties();
props.setProperty("user", "postgres");
props.setProperty("password", System.getenv("MOTHERDUCK_TOKEN"));
props.setProperty("sslmode", "verify-full");
props.setProperty("sslfactory", "org.postgresql.ssl.DefaultJavaSSLFactory");

Connection conn = DriverManager.getConnection(
"jdbc:postgresql://pg.us-east-1-aws.motherduck.com:5432/md:",
props
);

SSL notes

The PostgreSQL JDBC driver looks for a root certificate at ~/.postgresql/root.crt by default. To use your JVM's built-in truststore instead (which includes standard CAs like Let's Encrypt), set sslfactory=org.postgresql.ssl.DefaultJavaSSLFactory.

If certificate verification doesn't work in your environment, you can fall back to sslmode=require, which encrypts the connection but doesn't verify the server certificate.

For more details on SSL options, see SSL and certificate verification.