title | summary | toc |
---|---|---|
Connect to the Database |
How to connect to a CockroachDB cluster from your application |
true |
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.
Do the following:
- Set up a local CockroachDB cluster:
- Install a client driver or ORM framework.
{% include copy-clipboard.html %}
$ 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.
{% include copy-clipboard.html %}
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()
{% include {{page.version.version}}/app/for-a-complete-example-go.md %}
{% include copy-clipboard.html %}
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");
{{site.data.alerts.callout_success}} {% include {{page.version.version}}/app/pkcs8-gen.md %} {{site.data.alerts.end}}
{% include {{page.version.version}}/app/for-a-complete-example-java.md %}
{% include copy-clipboard.html %}
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'
)
{% include {{page.version.version}}/app/for-a-complete-example-python.md %}
You might also be interested in the following pages: