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


1 comment:

Unknown said...

Did you hear there's a 12 word sentence you can tell your man... that will induce intense feelings of love and instinctual attraction to you buried inside his chest?

Because deep inside these 12 words is a "secret signal" that triggers a man's instinct to love, treasure and care for you with his entire heart...

12 Words Who Fuel A Man's Desire Response

This instinct is so hardwired into a man's mind that it will drive him to try better than before to make your relationship the best part of both of your lives.

Matter of fact, triggering this powerful instinct is so important to achieving the best possible relationship with your man that the second you send your man a "Secret Signal"...

...You'll instantly find him open his mind and heart to you in such a way he never experienced before and he will perceive you as the only woman in the world who has ever truly tempted him.