Postgres With Go

Two things are required to interact with the database:

  1. A library
  2. A driver

Our library to interact with the database is ““database/sql” which is from the standard library.

While the driver is “github.com/jackc/pgx/v4” which provides also a toolkit or library to interact with the database, but in this case we will it only for getting the driver.

The below code is just one example:

package main

import (
	"database/sql"
	"fmt"

	_ "github.com/jackc/pgx/v4/stdlib" // stdlib is the package that provides the standard library driver. To be able to use database sql package
)

func main() {

	// pgx = Driver name defined by github.com/jackc/pgx/v4/ It we were using a different library, the driver would  be different.
	// host, user, password, dbname were the values used in the YAML file for the docker compose.
	db, err := sql.Open("pgx", "host=localhost port=5432 user=baloo password=junglebook dbname=lenslocked sslmode=disable")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		panic(err)
	}
	fmt.Println("Connected")

}

NOTE:

The blank character is used when importing the library (_ “github.com/jackc/pgx/v4/stdlib”) since we will not explicitly call or used anything from there.

However, the registering part will be done via init function within this library.

 Share!

 
comments powered by Disqus