We recommend using Java versions 8+ with CockroachDB.
Step 1. Start CockroachDB
- Use CockroachDB Cloud
- Use a Local Cluster
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, orccloud, a command-line interface (CLI) tool.- Cloud Console (GUI)
- ccloud CLI
Create a free cluster
Organizations without billing information on file can only create one CockroachDB Basic cluster.
- If you haven’t already, sign up for a CockroachDB Cloud account.
- Log in to your CockroachDB Cloud account.
- On the Clusters page, click Create cluster.
- On the Select a plan page, select Basic.
- On the Cloud & Regions page, select a cloud provider (GCP or AWS) in the Cloud provider section.
- 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.
- Click Next: Capacity.
- On the Capacity page, select Start for free. Click Next: Finalize.
- 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.- Enter a username in the SQL user field or use the one provided by default.
- Click Generate & save password.
- Copy the generated password and save it in a secure location.
- 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.- Select Java from the Select option/language dropdown.
- Select JDBC from the Select tool dropdown.
- Copy the command provided to set the
JDBC_DATABASE_URLenvironment 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:BasicExample.java file contains the code for INSERT, SELECT, and UPDATE SQL operations. The file also contains the main method of the program.
BasicExample, which is where the application logic lives.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.
main method of the app performs the following steps which roughly correspond to method calls in the BasicExample class.
| Step | Method |
|---|---|
1. Insert account data using a Map that corresponds to the input to INSERT on the backend | BasicExampleDAO.updateAccounts(Map balance) |
| 2. Transfer money from one account to another, printing out account balances before and after the transfer | BasicExampleDAO.transferFunds(UUID from, UUID to, BigDecimal amount) |
| 3. Insert random account data using JDBC’s bulk insertion support | BasicExampleDAO.bulkInsertRandomAccountData() |
| 4. Print out some account data | BasicExampleDAO.readAccounts(int limit) |
Step 3. Update the connection configuration
-
Navigate to the
example-app-java-jdbcdirectory: -
Set the
JDBC_DATABASE_URLenvironment variable to a JDBC-compatible connection string:-
Paste in the command you copied earlier:
Where is the JDBC connection string from the command you copied earlier.
-
Paste in the command you copied earlier:
-
Set the
JDBC_DATABASE_URLenvironment variable to a JDBC-compatible connection string:-
Use the
cockroach convert-urlcommand to convert the connection string that you copied earlier to a : -
Set the
JDBC_DATABASE_URLenvironment variable to the JDBC-compatible connection string:
-
Use the
Step 4. Run the code
Compile and run the code:Recommended Practices
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 :- is the name of the session variable.
- is the value of the session variable.
options parameter to make sure the JDBC connection URL is parsed correctly. For example, the following URL encoded options parameter:
options using setProperty:
- is the name of the session variable.
- is the value of the session variable.
-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 usermax:
client.max.key.pk8.
CockroachDB Cloud does not yet support certificate-based user authentication.
- If you haven’t already, .
-
Run the command:
This starts an insecure, single-node cluster.
-
Take note of the following connection information in the SQL shell welcome text:
You’ll use the
sqlconnection 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:BasicExample.java file contains the code for INSERT, SELECT, and UPDATE SQL operations. The file also contains the main method of the program.
BasicExample, which is where the application logic lives.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.
main method of the app performs the following steps which roughly correspond to method calls in the BasicExample class.
| Step | Method |
|---|---|
1. Insert account data using a Map that corresponds to the input to INSERT on the backend | BasicExampleDAO.updateAccounts(Map balance) |
| 2. Transfer money from one account to another, printing out account balances before and after the transfer | BasicExampleDAO.transferFunds(UUID from, UUID to, BigDecimal amount) |
| 3. Insert random account data using JDBC’s bulk insertion support | BasicExampleDAO.bulkInsertRandomAccountData() |
| 4. Print out some account data | BasicExampleDAO.readAccounts(int limit) |
Step 3. Update the connection configuration
-
Navigate to the
example-app-java-jdbcdirectory: -
Set the
JDBC_DATABASE_URLenvironment variable to a JDBC-compatible connection string:-
Paste in the command you copied earlier:
Where is the JDBC connection string from the command you copied earlier.
-
Paste in the command you copied earlier:
-
Set the
JDBC_DATABASE_URLenvironment variable to a JDBC-compatible connection string:-
Use the
cockroach convert-urlcommand to convert the connection string that you copied earlier to a : -
Set the
JDBC_DATABASE_URLenvironment variable to the JDBC-compatible connection string:
-
Use the
Step 4. Run the code
Compile and run the code:Recommended Practices
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 :- is the name of the session variable.
- is the value of the session variable.
options parameter to make sure the JDBC connection URL is parsed correctly. For example, the following URL encoded options parameter:
options using setProperty:
- is the name of the session variable.
- is the value of the session variable.
-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 usermax:
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 frominsert into foo (col1, col2, col3) values (1,2,3)intoinsert 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, theBasicExampleDAO.bulkInsertRandomAccountData() method).
Specifically, it does the following:
- Turn off auto-commit so you can manage the transaction lifecycle and thus the size of the batch inserts.
- Given an overall update size of 500 rows (for example), split it into batches of size 128 and execute each batch in turn.
- 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 whenStatement.setFetchSize() is used.

