Db connection error

My file structure is
– main.go
–config
—db.go
and inside db.go i am connection my program with db

 package config

import (
     "database/sql"
   _ "github.com/lib/pq"
	"fmt"
)

var Db *sql.DB

func init() {
Db, err := sql.Open("postgres",
	"postgres://postgres:Yfehsp2203@localhost/postgres?sslmode=disable")

if err != nil {
	panic("Can not connect to DB")
}

if err = Db.Ping(); err != nil {
	panic("Pingin error")
}

fmt.Println("Successfully connected")
}

and it connects fine but when i try to access db inside mb main.go

if err  := config.Db.Ping(); err != nil {
	panic("Pingin error")
}
fmt.Println("DATABASE IS ON")

just pinging there are tons and tons of errors and i do not understand why help please!!!

can you post more design code to understand ?

Db is shadowed in init():

Db, err := sql.Open("postgres",
	"postgres://postgres:Yfehsp2203@localhost/postgres?sslmode=disable")

Avoid shadowing Db and assign to the global Db with:

var err error
Db, err = sql.Open("postgres",
	"postgres://postgres:Yfehsp2203@localhost/postgres?sslmode=disable")
1 Like

Nice, now its working but could you explain why ? and what does shadowed mean ?

:= creates the variables on its left hand side which do not exist in the current scope. The current scope for this line is the init() function. Since there is no previous declaration of Db in init() (the current scope) Db is created by := (along with err).

Using = instead requires declaring err first (otherwise there would be an undeclared variable). Go can then find the global Db by first looking the in the current scope, init(), not finding Db and then looking in the current scope’s parent, the global scope, where Db is declared.

Shadowing is when a variable in the current scope masks/blocks/prevents access to a variable with the same name in a parent scope.

See Scope and Shadowing in Go for a longer explanation with example code.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.