Connect to the Database

On this page Carat arrow pointing down
Warning:
CockroachDB v20.1 is no longer supported as of November 12, 2021. For more details, refer to 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 local cluster to a bank database by a user named maxroach. Depending on your cluster's configuration, you may need to edit this connection string.

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

Before you begin

Make sure you have already:

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");

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:

See also

Reference information related to this task:

Other common tasks:


Yes No
On this page

Yes No