Skip to main content
This tutorial shows you how to build a simple CRUD Java application with CockroachDB and the Java JDBC driver.
We recommend using Java versions 8+ with CockroachDB.
For a sample app and tutorial that uses Spring Data JDBC and CockroachDB, see .

Step 1. Start CockroachDB

Choose your installation method

You can create a CockroachDB Basic cluster using either the CockroachDB Cloud Console, a web-based graphical user interface (GUI) tool, or ccloud, a command-line interface (CLI) tool.

Create a free cluster

Organizations without billing information on file can only create one CockroachDB Basic 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 Select a plan page, select Basic.
  5. On the Cloud & Regions page, select a cloud provider (GCP or AWS) in the Cloud provider section.
  6. In the Regions section, select a region for the cluster. Refer to for the regions where CockroachDB Basic clusters can be deployed. To create a multi-region cluster, click Add region and select additional regions.
  7. Click Next: Capacity.
  8. On the Capacity page, select Start for free. Click Next: Finalize.
  9. On the Finalize page, click Create cluster. Your cluster will be created in a few seconds and the Create SQL user dialog will display.

Create a SQL user

The Create SQL user dialog allows you to create a new SQL user and password.
  1. Enter a username in the SQL user field or use the one provided by default.
  2. Click Generate & save password.
  3. Copy the generated password and save it in a secure location.
  4. Click Next. Currently, all new SQL users are created with admin privileges. For more information and to change the default settings, see .

Get the connection string

The Connect to cluster dialog shows information about how to connect to your cluster.
  1. Select Java from the Select option/language dropdown.
  2. Select JDBC from the Select tool dropdown.
  3. Copy the command provided to set the JDBC_DATABASE_URL environment variable.
The JDBC connection URL is pre-populated with your username, password, cluster name, and other details. Your password, in particular, will be provided only once. Save it in a secure place (Cockroach Labs recommends a password manager) to connect to your cluster in the future. If you forget your password, you can reset it by going to the SQL Users page for the cluster, found at https://cockroachlabs.cloud/cluster/<CLUSTER ID>/users.

Step 2. Get the code

Clone the code’s GitHub repo:
The project has the following directory structure:
The BasicExample.java file contains the code for INSERT, SELECT, and UPDATE SQL operations. The file also contains the main method of the program.
The sample app uses JDBC and the Data Access Object (DAO) pattern to map Java methods to SQL operations. It consists of two classes:
  1. BasicExample, which is where the application logic lives.
  2. BasicExampleDAO, which is used by the application to access the data store (in this case CockroachDB). This class also includes a helper function ( runSql ) that runs SQL statements inside a transaction, as needed.
The main method of the app performs the following steps which roughly correspond to method calls in the BasicExample class.
StepMethod
1. Insert account data using a Map that corresponds to the input to INSERT on the backendBasicExampleDAO.updateAccounts(Map balance)
2. Transfer money from one account to another, printing out account balances before and after the transferBasicExampleDAO.transferFunds(UUID from, UUID to, BigDecimal amount)
3. Insert random account data using JDBC’s bulk insertion supportBasicExampleDAO.bulkInsertRandomAccountData()
4. Print out some account dataBasicExampleDAO.readAccounts(int limit)
It does all of the above using the practices we recommend for using JDBC with CockroachDB, which are listed in the Recommended Practices section below.

Step 3. Update the connection configuration

  1. Navigate to the example-app-java-jdbc directory:
  2. Set the JDBC_DATABASE_URL environment variable to a JDBC-compatible connection string:
    1. Paste in the command you copied earlier:
      Where is the JDBC connection string from the command you copied earlier.
  3. Set the JDBC_DATABASE_URL environment variable to a JDBC-compatible connection string:
    1. Use the cockroach convert-url command to convert the connection string that you copied earlier to a :
    2. Set the JDBC_DATABASE_URL environment variable to the JDBC-compatible connection string:

Step 4. Run the code

Compile and run the code:
The output will look like the following:

Set session variables

can be set in the JDBC connection string or as properties of the JDBC data source. To set the session variable in the JDBC connection string, add them to the :
Where:
  • is the name of the session variable.
  • is the value of the session variable.
URL encode the options parameter to make sure the JDBC connection URL is parsed correctly. For example, the following URL encoded options parameter:
is equivalent to:
To set session variables as properties of the JDBC data source, set options using setProperty:
Where:
  • is the name of the session variable.
  • is the value of the session variable.
To add more than one session variable, append additional -c settings:

Generate PKCS8 keys for user authentication

You can pass the to to generate a key in PKCS#8 format, which is the standard key encoding format in Java. For example, if you have the user max:
The generated PKCS8 key will be named client.max.key.pk8.
CockroachDB Cloud does not yet support certificate-based user authentication.
  1. If you haven’t already, .
  2. Run the command:
    This starts an insecure, single-node cluster.
  3. Take note of the following connection information in the SQL shell welcome text:
    You’ll use the sql connection string to connect to the cluster later in this tutorial.
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:
The project has the following directory structure:
The BasicExample.java file contains the code for INSERT, SELECT, and UPDATE SQL operations. The file also contains the main method of the program.
The sample app uses JDBC and the Data Access Object (DAO) pattern to map Java methods to SQL operations. It consists of two classes:
  1. BasicExample, which is where the application logic lives.
  2. BasicExampleDAO, which is used by the application to access the data store (in this case CockroachDB). This class also includes a helper function ( runSql ) that runs SQL statements inside a transaction, as needed.
The main method of the app performs the following steps which roughly correspond to method calls in the BasicExample class.
StepMethod
1. Insert account data using a Map that corresponds to the input to INSERT on the backendBasicExampleDAO.updateAccounts(Map balance)
2. Transfer money from one account to another, printing out account balances before and after the transferBasicExampleDAO.transferFunds(UUID from, UUID to, BigDecimal amount)
3. Insert random account data using JDBC’s bulk insertion supportBasicExampleDAO.bulkInsertRandomAccountData()
4. Print out some account dataBasicExampleDAO.readAccounts(int limit)
It does all of the above using the practices we recommend for using JDBC with CockroachDB, which are listed in the Recommended Practices section below.

Step 3. Update the connection configuration

  1. Navigate to the example-app-java-jdbc directory:
  2. Set the JDBC_DATABASE_URL environment variable to a JDBC-compatible connection string:
    1. Paste in the command you copied earlier:
      Where is the JDBC connection string from the command you copied earlier.
  3. Set the JDBC_DATABASE_URL environment variable to a JDBC-compatible connection string:
    1. Use the cockroach convert-url command to convert the connection string that you copied earlier to a :
    2. Set the JDBC_DATABASE_URL environment variable to the JDBC-compatible connection string:

Step 4. Run the code

Compile and run the code:
The output will look like the following:

Set session variables

can be set in the JDBC connection string or as properties of the JDBC data source. To set the session variable in the JDBC connection string, add them to the :
Where:
  • is the name of the session variable.
  • is the value of the session variable.
URL encode the options parameter to make sure the JDBC connection URL is parsed correctly. For example, the following URL encoded options parameter:
is equivalent to:
To set session variables as properties of the JDBC data source, set options using setProperty:
Where:
  • is the name of the session variable.
  • is the value of the session variable.
To add more than one session variable, append additional -c settings:

Generate PKCS8 keys for user authentication

You can pass the to to generate a key in PKCS#8 format, which is the standard key encoding format in Java. For example, if you have the user max:
The generated PKCS8 key will be named client.max.key.pk8.

Use IMPORT INTO to read in large data sets

If you are trying to get a large data set into CockroachDB all at once (a bulk import), avoid writing client-side code altogether and use the statement instead. It is much faster and more efficient than making a series of and . It bypasses the altogether and writes directly to the of the database. For more information about importing data from PostgreSQL, see . For more information about importing data from MySQL, see .

Use reWriteBatchedInserts for increased speed

We strongly recommend setting reWriteBatchedInserts=true; we have seen 2-3x performance improvements with it enabled. From the JDBC connection parameters documentation:
This will change batch inserts from insert into foo (col1, col2, col3) values (1,2,3) into insert into foo (col1, col2, col3) values (1,2,3), (4,5,6) this provides 2-3x performance improvement

Use a batch size of 128

PGJDBC’s batching support only works with powers of two, and will split batches of other sizes up into multiple sub-batches. This means that a batch of size 128 can be 6x faster than a batch of size 250. The code snippet below shows a pattern for using a batch size of 128, and is taken from the longer example above (specifically, the BasicExampleDAO.bulkInsertRandomAccountData() method). Specifically, it does the following:
  1. Turn off auto-commit so you can manage the transaction lifecycle and thus the size of the batch inserts.
  2. Given an overall update size of 500 rows (for example), split it into batches of size 128 and execute each batch in turn.
  3. Finally, commit the batches of statements you’ve just executed.

Retrieve large data sets in chunks using cursors

CockroachDB now supports the PostgreSQL wire-protocol cursors for implicit transactions and explicit transactions executed to completion. This means the PGJDBC driver can use this protocol to stream queries with large result sets. This is much faster than . For instructions showing how to use cursors in your Java code, see Getting results based on a cursor from the PGJDBC documentation. Note that interleaved execution (partial execution of multiple statements within the same connection and transaction) is not supported when Statement.setFetchSize() is used.

Connection pooling

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

What’s next?

Read more about using the Java JDBC driver. You might also be interested in the following pages: