Connect with the Go driver

DataStax recommends the Data API and clients for Serverless (vector) databases. You can use the Data API to run CQL statements on tables in Serverless (vector) databases.

DataStax recommends drivers only for Serverless (non-vector) databases, legacy applications that rely on a driver, or CQL functions that aren’t supported by the Data API. For more information, see Connect to Astra DB Serverless databases.

Because Astra DB is based on Apache Cassandra®, you can use Cassandra drivers to connect to your Astra DB Serverless databases.

To use the Apache Cassandra GoCQL driver (gocql) with Astra DB Serverless databases, use the gocql-astra package. This package includes GoCQL and additional support for connections to Astra DB.

The gocql-astra package provides a custom gocql.HostDialer that facilitates GoCQL connections to Astra DB because GoCQL doesn’t directly support connections to Astra DB.

This quickstart explains how to use gocql-astra to connect gocql to your database, create a table, read and write data, and then delete the rows and table.

gocql-astra doesn’t support gocql 2.x or the vector type

gocql version 2.0 introduced support for the vector type. However, gocql-astra doesn’t support gocql version 2.0, so you cannot use gocql 2.x features, such as the vector type, with gocql-astra.

Until gocql-astra version 2.0 is released, gocql-astra requires gocql 1.x. Manually modifying gocql-astra to pull gocql 2.x can cause errors due to breaking changes in gocql 2.0. For more information, see the GitHub issue for gocql 2.0 support in gocql-astra.

Prerequisites

  1. Install Go version 1.22 or later.

  2. Create a database.

  3. Download your database’s Secure Connect Bundle (SCB).

    For multi-region databases, download the SCB for a region that is geographically close to your application to reduce latency.

    If you need to connect to multiple regions in the same application, you need the SCB for each region, and your driver code must instantiate one root object (session) for each region. For more information, see Best practices for Cassandra drivers.

  4. Set the following environment variables:

Install gocql-astra

In the root of your Go project directory, add gocql-astra:

go get github.com/datastax/gocql-astra

gocql-astra includes the gocql package.

Connect to your database

gocql-astra provides support to connect gocql to Astra DB Serverless databases.

Connect with an application token only

Write a script to connect gocql to your database using the APPLICATION_TOKEN and DATABASE_ID environment variables.

The following example imports the necessary classes, sets up a session, authenticates with an application token, and runs a SELECT statement on the system.local table. You can replace the example SELECT statement with any CQL statement that you want to run against a keyspace and table in your database.

package main

import (
    "fmt"
    "log"
    "os"
    "time"

    gocqlastra "github.com/datastax/gocql-astra"
    "github.com/gocql/gocql"
)

func main() {

    var err error

    var cluster *gocql.ClusterConfig

    if len(os.Getenv("APPLICATION_TOKEN")) > 0 {

        if len(os.Getenv("DATABASE_ID")) == 0 {
            panic("database ID is required when using a token")
        }
    }

    cluster, err = gocqlastra.NewClusterFromURL("https://api.astra.datastax.com", os.Getenv("DATABASE_ID"), os.Getenv("APPLICATION_TOKEN"), 10*time.Second)

    if err != nil {
        log.Fatalf("unable to load cluster %s from astra: %v", os.Getenv("APPLICATION_TOKEN"), err)
    }

    cluster.Timeout = 30 * time.Second
    start := time.Now()
    session, err := gocql.NewSession(*cluster)
    elapsed := time.Now().Sub(start)

    if err != nil {
        log.Fatalf("unable to connect session: %v", err)
    }

    fmt.Println("Making the query now")

    iter := session.Query("SELECT release_version FROM system.local").Iter()

    var version string

    for iter.Scan(&version) {
        fmt.Println(version)
    }

    if err = iter.Close(); err != nil {
        log.Printf("error running query: %v", err)
    }

    fmt.Printf("Connection process took %s
", elapsed)

    if err != nil {
        log.Fatalf("unable to connect session: %v", err)
    }

}

Enable SSL encryption with an SCB

To connect with SSL encryption, use the gocql-astra method that accepts an SCB path and application token:

  1. Set an environment variable for your database’s SCB zip file, such as ASTRA_DB_SECURE_BUNDLE_PATH. For more information, see Prerequisites.

  2. Run a script such as the following to connect to your database. This code imports the necessary classes, sets up a session, and authenticates with an SCB.

    In the authentication credentials, the literal string token is required for successful authentication. For more information, see Token details.

    package main
    
    import (
        "fmt"
        "log"
        "os"
        "time"
    
        gocqlastra "github.com/datastax/gocql-astra"
        "github.com/gocql/gocql"
    )
    
    func main() {
    
        var cluster *gocql.ClusterConfig
    
        cluster, err := gocqlastra.NewClusterFromBundle(os.Getenv("ASTRA_DB_SECURE_BUNDLE_PATH"),
            "token", os.Getenv("APPLICATION_TOKEN"), 30*time.Second)
    
        if err != nil {
            panic("unable to load the bundle")
        }
        cluster.Timeout = 30 * time.Second
    
        session, err := gocql.NewSession(*cluster)
    
        if err != nil || session == nil {
            log.Fatalf("unable to connect session: %v", err)
        } else {
            fmt.Println("Success!")
        }
    
    }

Run commands

With gocql-astra, your scripts can use gocql commands to perform operations on your database.

For example, the following sample script performs these operations:

  • Defines the Book object

  • Connects to the database with an application token

  • Create a books table

  • Inserts two rows into the table

  • Retries the inserted rows

  • Updates one row

  • Deletes one row

  • Deletes the table

main.go
package main

import (
    "fmt"
    "log"
    "os"
    "time"

    gocqlastra "github.com/datastax/gocql-astra"
    "github.com/gocql/gocql"
)

type Book struct {
    ID     gocql.UUID
    Title  string
    Author string
    Year   int
}

func main() {

    var err error

    var cluster *gocql.ClusterConfig

    if len(os.Getenv("APPLICATION_TOKEN")) > 0 {
        if len(os.Getenv("DATABASE_ID")) == 0 {
            panic("database ID is required when using a token")
        }
    }

    fmt.Println("Creating the cluster now")

    cluster, err = gocqlastra.NewClusterFromURL("https://api.astra.datastax.com", os.Getenv("DATABASE_ID"), os.Getenv("APPLICATION_TOKEN"), 20*time.Second)
    if err != nil {
        log.Fatalf("unable to load cluster %s from astra: %v", os.Getenv("APPLICATION_TOKEN"), err)
    }
    cluster.Timeout = 30 * time.Second
    session, err := gocql.NewSession(*cluster)

    if err != nil {
        log.Fatalf("unable to connect session: %v", err)
    }

    defer session.Close()

    // Delete the table
    if err := session.Query(`DROP TABLE IF EXISTS library.books`).Exec(); err != nil {
        fmt.Println("Dropping table to clean for examples.")
    }

    // Create the table
    fmt.Println("Creating the table now")
    if err := session.Query(`CREATE TABLE library.books ( id uuid PRIMARY KEY, title text, author text, year int );`).Exec(); err != nil {
        log.Fatal(err)
    }
    // Create Rows
    newBook := Book{
        ID:     gocql.TimeUUID(),
        Title:  "Go Programming",
        Author: "John Doe",
        Year:   2023,
    }

    secondBook := Book{
        ID:     gocql.TimeUUID(),
        Title:  "Zen and the Art of Go",
        Author: "Jane Doe",
        Year:   2023,
    }

    fmt.Println("Adding the books now:")

    if err := session.Query(`INSERT INTO library.books (id, title, author, year) VALUES (?, ?, ?, ?)`,
        newBook.ID, newBook.Title, newBook.Author, newBook.Year).Exec(); err != nil {
        log.Fatal(err)
    }

    if err := session.Query(`INSERT INTO library.books (id, title, author, year) VALUES (?, ?, ?, ?)`,
        secondBook.ID, secondBook.Title, secondBook.Author, secondBook.Year).Exec(); err != nil {
        log.Fatal(err)
    }

    fmt.Println("Querying the books now:")
    iter := session.Query(`SELECT id, title, author, year FROM library.books`).Iter()

    var books []Book
    var book Book
    for iter.Scan(&book.ID, &book.Title, &book.Author, &book.Year) {
        books = append(books, book)
    }

    if err := iter.Close(); err != nil {
        log.Fatal(err)
    }

    // Print all books
    for _, book := range books {
        fmt.Println("Book:", book)
    }

    // Update
    updatedBook := Book{
        ID:     newBook.ID,
        Title:  "Advanced Go Programming",
        Author: "John Doe",
        Year:   2024,
    }

    if err := session.Query(`UPDATE library.books SET title = ?, author = ?, year = ? WHERE id = ?`,
        updatedBook.Title, updatedBook.Author, updatedBook.Year, updatedBook.ID).Exec(); err != nil {
        log.Fatal(err)
    }

    // Delete
    if err := session.Query(`DELETE FROM library.books WHERE id = ?`, newBook.ID).Exec(); err != nil {
        log.Fatal(err)
    }

}

To run the sample script, do the following:

  1. In your Go project directory, create a main.go file.

  2. Copy the sample script to main.go, and then save the file.

    The sample script creates and deletes a table. If you run it as is, the books table won’t exist in your database after the script ends. Consider breaking the sample script into smaller scripts, or comment out the DELETE commands, if you want to preserve the books table for additional testing.

  3. Run main.go:

    go run main.go

Next steps

Next, extend or modify this script to run other commands against your database or connect to other databases. For more information, see the following:

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM