How to connect to CARTO from external applications using JDBC
This tutorial demonstrates how to connect with your CARTO database using a JDBC connection. We strongly recommend reading the Direct SQL Connection article to learn more about that feature before reading this one.
This tutorial assumes that you have already installed a Java Runtime Environment in your computer, version 8 or newer.
Configuration
-
Download the PostgreSQL JDBC driver from https://jdbc.postgresql.org/.
-
Add the downloaded JAR file to your classpath
-
Create a JDBC connection in your Java program. If you want to use TLS certificates for client authentication, you must include the certificate files in the connection properties. We must use the DER PKCS #8 private key file.
String url = "jdbc:postgresql://{hostname}:{port}/cartodb";
Properties props = new Properties();
props.setProperty("user","username");
props.setProperty("password","API key");
props.setProperty("ssl","true");
props.setProperty("sslmode","verify-full");
props.setProperty("sslcert","./client.crt");
props.setProperty("sslkey","./client.key.pk8");
props.setProperty("sslrootcert","./server_ca.pem");
Connection conn = DriverManager.getConnection(url, props);
System.out.println("Connection created");
conn.close();
System.out.println("Connection closed");
- If you don’t want or can’t use client authentication with TLS certificates, you can change the
sslmode
option toverify-ca
and remove thesslcert
andsslkey
properties:
String url = "jdbc:postgresql://{hostname}:{port}/cartodb";
Properties props = new Properties();
props.setProperty("user","username");
props.setProperty("password","API key");
props.setProperty("ssl","true");
props.setProperty("sslmode","verify-ca");
props.setProperty("sslrootcert","./server_ca.pem");
Connection conn = DriverManager.getConnection(url, props);
System.out.println("Connection created");
conn.close();
System.out.println("Connection closed");