Tuesday, January 14, 2020


How to connect GOLANG to postgresSQL#GOLANG, #postgres, #postgresSQL, #Code, #program


Team: Today we will learn how to connect GOLANG with postgresSQL, 
Prerequisites: you will require GOLANG, postgresSQL and Visual Studio Code.

in Visual Studio Code, create root workspace 

c:\project\postgresSQL

Create 3 sub folders 

  • bin
  • pkg
  • src

GoLANG folders

Start Terminial -> CTRL + `

Check golang environment variable -> go env 

set GOBIN and GOPATH 

export GOBIN=/c/project/postgres/bin
export GOPATH=/c/project/postgres

change folder to src and get postgresSQL driver




now src folder should have github package and we are all set to write golang / postgresSQL progam 

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
)

type product struct {
    ProductID   int64
    ProductName string
    ProductDesc string
}

func main() {

    connStr := "user=postgres dbname=inventory password=1234 host=localhost port=5432 sslmode=disable"
    dberr := sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
    fmt.Println("connection success")

    rowserr := db.Query("SELECT * from public.\"products\" order by \"ProductID\"")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    for rows.Next() {
        var prodID string
        var prodName string
        var prodDesc string
        err := rows.Scan(&prodID, &prodName, &prodDesc)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s .. %s .. %s\n", prodID, prodName, prodDesc)
    }
}

compile and install code 

go build prod.go
go install prod.go

install creates prod.exe in bin folder

start command prompt
go to bin sub folder
run prod.exe










Congratulations!!! you did excellent Job!!!
email me if you have any qusetion!!!

postgres products data in database

postgres output