The 2024 CrateDB architecture guide covering all key concepts is out.

Download now
Skip to content
Product

How to Connect with Go

Effortlessly integrate CrateDB with Go applications via PostgreSQL Go driver.

1200px-Go_Logo_Blue.svg

Connecting to CrateDB with Go is facilitated through the utilization of pgx, a pure Go driver and toolkit specifically designed for PostgreSQL. With its focus on providing a reliable interface, pgx significantly streamlines integrating and interacting with CrateDB, ensuring efficient handling of PostgreSQL-specific features within Go applications. 

        

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/jackc/pgx/v5"
)

func main() {
	conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
		os.Exit(1)
	}
	defer conn.Close(context.Background())

	var greeting string
	err = conn.QueryRow(context.Background(), "select 'Hello, world!'").Scan(&greeting)
	if err != nil {
		fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		os.Exit(1)
	}

	fmt.Println(greeting)
}
        
        
        

The pgx driver for CrateDB delivers PostgreSQL-specific features like LISTEN/NOTIFY and COPY within Go applications. Additionally, the toolkit component comprises packages that implement PostgreSQL functionalities, serving as a foundation for various database-related tasks such as parsing the PostgreSQL Wire Protocol and type mapping between PostgreSQL and Go. These underlying packages are versatile and can be utilized to implement alternative drivers, proxies, load balancers, and more.

Read the technical documentation for further details on establishing connections with CrateDB in Go applications.

Additional resources