Connect to a PostgreSQL database using GO

This blog post is related to this good pgx – PostgreSQL Driver and Toolkit that is used to access a PostgresSQL database with GO. My blog post contains minor modifications of an example in that toolkit. You can find the source code related to my blog post in that GitHub project.

Objective

Create a connection to a PostgreSQL database and execute a query on a table to verify the connection, in a locally running GO application.

Note: You need a running PostgreSQL database and a table called widgets, which maybe doesn’t exist in your database.

Example setup steps

Step 1: Create a folder

mkdir go-access-postgres-example

Step 2: Navigate to the folder

cd go-access-postgres-example

Step 3: Create a mod file

go mod init example/gopostgressql
  • Example output:
go: creating new go.mod: module example/gopostgressql

Step 2: Create a go file

touch gopostgressql.go

Step 3: Copy the code into the created file

package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
        // urlExample := "postgres://username:password@localhost:5432/database_name"
	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)
	} else {
	   fmt.Printf("Connected to the DB: true [" + os.Getenv("DATABASE_URL") + "] \n")
	}
	defer conn.Close(context.Background())

	var name string
	var weight int64
	err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
	if err != nil {
	        fmt.Printf("Connected to the DB: true\n")
		fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		os.Exit(1)
	}

	fmt.Println(name, weight)
}

Step 4: Import the needed packages

go get github.com/jackc/pgx/v4

Step 5: Set the enviornment variable

export DATABASE_URL="postgres://username:password@localhost:5432/database_name"

Note: Don’t forget to insert your DATABASE_URL.

Step 5: Execute the go program

go run  .

Summary

The pgx – PostgreSQL Driver and Toolkit works well with GO and I will use it for my next example.


I hope this was useful for you and let’s see what’s next?

Greetings,

Thomas

#go, #postgressql, #buildlabs4saas

One thought on “Connect to a PostgreSQL database using GO

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.