Build a Hello World App with CockroachDB and JDBC

This tutorial shows you how build a simple Hello World Java application with CockroachDB and the JDBC driver.

Step 1. Start CockroachDB

Create a free cluster

  1. If you haven't already, sign up for a CockroachDB Cloud account.
  2. Log in to your CockroachDB Cloud account.
  3. On the Clusters page, click Create Cluster.
  4. On the Create your cluster page, select CockroachDB Serverless.

    Note:

    This cluster will be free forever.

  5. Click Create your free cluster.

Your cluster will be created in approximately 20-30 seconds.

Set up your cluster connection

  1. Navigate to the cluster's SQL Users page, and create a new user, with a new password.

  2. Navigate to the Cluster Overview page, select Connect, and, under the Connection String tab, download the cluster certificate.

  3. Take note of the connection string provided. You'll use it to connect to the database later in this tutorial.

  1. If you haven't already, download the CockroachDB binary.
  2. Run the cockroach start-single-node command:

    icon/buttons/copy
    $ cockroach start-single-node --advertise-addr 'localhost' --insecure
    

    This starts an insecure, single-node cluster.

  3. Take note of the following connection information in the SQL shell welcome text:

    CockroachDB node starting at 2021-08-30 17:25:30.06524 +0000 UTC (took 4.3s)
    build:               CCL v21.1.6 @ 2021/07/20 15:33:43 (go1.15.11)
    webui:               http://localhost:8080
    sql:                 postgresql://root@localhost:26257?sslmode=disable
    

    You'll use the sql connection string to connect to the cluster later in this tutorial.

Warning:

The --insecure flag used in this tutorial is intended for non-production testing only. To run CockroachDB in production, use a secure cluster instead.

Step 2. Get the code

Clone the code's GitHub repo:

icon/buttons/copy
$ git clone https://github.com/cockroachlabs/hello-world-java-jdbc/

Check out the cockroachcloud branch:

icon/buttons/copy

git checkout cockroachcloud

The app/src/main/java/example/app/App.java file contains all of the code for the sample Hello World app:

icon/buttons/copy
package example.app;

import org.postgresql.ds.PGSimpleDataSource;

public class App {

    public static void main(String[] args) {

        try {
            PGSimpleDataSource ds = new PGSimpleDataSource();
            ds.setServerNames(new String[]{"localhost"});
            ds.setPortNumbers(new int[]{26257});
            ds.setDatabaseName("defaultdb");
            ds.setUser("root");
            ds.setSsl(false);
            ds.setSslMode("disable");
            ds.setApplicationName("App");
            System.out.println("Hey! You connected to your CockroachDB cluster.");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

The main method of this program does the following:

  1. Attempts to connect to a running cluster, given some connection information.
  2. Prints a message to the terminal about the connection status.

Step 3. Run the code

Update the connection parameters

In a text editor modify app/src/main/java/example/app/App.java with the settings to connect to the cluster:

icon/buttons/copy
ds.setServerNames(new String[]{"{globalhost}"});
ds.setDatabaseName("{cluster_name}.defaultdb");
ds.setUser("{username}");
ds.setPassword("{password}");
ds.setSslRootCert(System.getenv("{path to the CA certificate}"));

Where:

  • {username} and {password} specify the SQL username and password that you created earlier.
  • {globalhost} is the name of the CockroachDB Cloud free tier host (e.g., free-tier.gcp-us-central1.cockroachlabs.cloud).
  • {path to the CA certificate} is the path to the cc-ca.crt file that you downloaded from the CockroachDB Cloud Console.
  • {cluster_name} is the name of your cluster.
Note:

If you are using the connection string that you copied from the Connection info modal, your username, password, hostname, and cluster name will be pre-populated.

Tip:

For guidance on connection pooling, with an example using JDBC and HikariCP, see Connection Pooling.

Compile and run the code:

icon/buttons/copy
./gradlew run

The app will prompt you for the password to the demo cluster:

> Task :app:run
Enter the demo password:
<=========----> 75% EXECUTING [22s]

Enter the password.

The output should look like this:

Hey! You successfully connected to your CockroachDB cluster.

See also

You might also be interested in the following pages:

YesYes NoNo