Connect to the Database

Warning:
Cockroach Labs will stop providing Assistance Support for this version on May 10, 2022. Prior to that date, upgrade to a more recent version to continue receiving support. For more details, see the Release Support Policy.

This page has instructions for connecting to a CockroachDB cluster from your application using various programming languages. Each example shows a connection string for a secure cluster to a bank database. Depending on your cluster's configuration, you may need to edit this connection string.

The connection strings listed on this page set the required authentication options to connect to local clusters. Local clusters use self-signed SSL certificates.

For a reference that lists all of the supported cluster connection parameters, see Connection Parameters.

Before you begin

Do the following:

Connect

icon/buttons/copy
$ cockroach sql --certs-dir=certs --host=localhost:26257

For more information about how to use the built-in SQL client, see the cockroach sql reference docs.

icon/buttons/copy
import (
    "database/sql"
    "fmt"
    "log"
    _ "github.com/lib/pq"
)

db, err := sql.Open("postgres",
        "postgresql://maxroach@localhost:26257/bank?ssl=true&sslmode=require&sslrootcert=certs/ca.crt&sslkey=certs/client.maxroach.key&sslcert=certs/client.maxroach.crt")
if err != nil {
    log.Fatal("error connecting to the database: ", err)
}
defer db.Close()

For complete examples, see:

icon/buttons/copy
import java.sql.*;
import javax.sql.DataSource;

PGSimpleDataSource ds = new PGSimpleDataSource();
ds.setServerName("localhost");
ds.setPortNumber(26257);
ds.setDatabaseName("bank");
ds.setUser("maxroach");
ds.setPassword(null);
ds.setSsl(true);
ds.setSslMode("require");
ds.setSslCert("certs/client.maxroach.crt");
ds.setSslKey("certs/client.maxroach.key.pk8");
ds.setReWriteBatchedInserts(true); // add `rewriteBatchedInserts=true` to pg connection string
ds.setApplicationName("BasicExample");
Tip:

You can pass the --also-generate-pkcs8-key flag to cockroach cert 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:

icon/buttons/copy
$ cockroach cert create-client max --certs-dir=certs --ca-key=my-safe-directory/ca.key --also-generate-pkcs8-key

The generated PKCS8 key will be named client.max.key.pk8.

For complete examples, see:

icon/buttons/copy
import psycopg2

conn = psycopg2.connect(
    database='bank',
    user='maxroach',
    sslmode='require',
    sslrootcert='certs/ca.crt',
    sslkey='certs/client.maxroach.key',
    sslcert='certs/client.maxroach.crt',
    port=26257,
    host='localhost'
)

For complete examples, see:

What's next?

You might also be interested in the following pages:

YesYes NoNo