title | summary | toc | referral_id | docs_area | |
---|---|---|---|---|---|
Build a Go App with CockroachDB the Go pq Driver |
Learn how to use CockroachDB from a simple Go application with the Go pq driver. |
true |
false |
docs_go_pq |
get_started |
{% include {{ page.version.version }}/filter-tabs/crud-go.md %}
This tutorial shows you how build a simple Go application with CockroachDB and the Go pq driver.
{% include {{ page.version.version }}/setup/sample-setup.md %}
Clone the code's GitHub repo:
{% include_cached copy-clipboard.html %}
$ git clone https://github.com/cockroachlabs/hello-world-go-pq
-
Navigate to the
hello-world-go-pq
directory:{% include_cached copy-clipboard.html %}
$ cd hello-world-go-pq
-
Set the
DATABASE_URL
environment variable to the connection string for your cluster:{% include_cached copy-clipboard.html %}
export DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable"
{% include_cached copy-clipboard.html %}
export DATABASE_URL="{connection-string}"
Where
{connection-string}
is the connection string you copied earlier.
You can now run the code sample (main.go
) provided in this tutorial to do the following:
-
Create a table.
-
Insert some rows into the table you created.
-
Read values from the table.
-
Execute a batch of statements as an atomic transaction.
Note that CockroachDB may require the client to retry a transaction in the case of read/write contention. The CockroachDB Go client includes a generic retry function (
ExecuteTx()
) that runs inside a transaction and retries it as needed. The code sample shows how you can use this function to wrap SQL statements.
-
Initialize the module:
{% include_cached copy-clipboard.html %}
$ go mod init basic-sample && go mod tidy
-
Run the code:
{% include_cached copy-clipboard.html %}
$ go run main.go
The output should be:
Balances: 1 1000 2 250 Success Balances: 1 900 2 350
Read more about using the Go pq driver.
{% include {{ page.version.version }}/app/see-also-links.md %}