How can I open db connection on package level?

I have a structure like this

-project
--main.go
--user
  ---db.go

Inside db.go i have function which opens db connection

func InitDB(dbName string) {
db, err := sql.Open("mysql", dbName)
if err != nil {
	log.Fatal("Retard alert connection to db")
}

if err = db.Ping(); err != nil {
	log.Fatal("Error Ping")
 }
}

I call it from the very begining in main

func main() {
    	userStaff.InitDB("root:Yfehsp2203@tcp(127.0.0.1:3306)/golangdb")
        http.HandleFunc("/", index)
        http.HandleFunc("/login", login)
        http.HandleFunc("/signup", signUp)
        http.ListenAndServe(":8080", nil)
}

and also inside db.go i have another function and inside this function i want to insert some values into my db.
And without opening another connection it does not work, it works fine if i write one more time

db, err := sql.Open("mysql", myDBname)
if err != nil {
	log.Fatal("Retard alert connection to db")
}

how can i open db connecion only one inside my db.go and use it inside any function ?

File: db.go

package funcs

import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"time"
)

var DbConn *sql.DB

func DbOpenConn() (*sql.DB, error) {
    DbConn, err := sql.Open("mysql", "your_connection_string")
    CheckErr(err)

    DbConn.SetMaxIdleConns(0)
    DbConn.SetMaxOpenConns(200)
    DbConn.SetConnMaxLifetime(time.Second * 5)
    return DbConn, err
}

File: test.go

func Test_Index(w http.ResponseWriter, r *http.Request) {

    db := funcs.DbConn
    //... your code
}
1 Like

unfortunately it does not work db.go

var DbConn *sql.DB
func InitDB(dbName string) (*sql.DB, error) {
DbConn, err := sql.Open("mysql", dbName)
if err != nil {
	log.Fatal("■■■■■■ Alert")
}

DbConn.SetMaxIdleConns(0)
DbConn.SetMaxOpenConns(200)
DbConn.SetConnMaxLifetime(0)
return DbConn, err
}


func Login(r *http.Request) int {
email := r.FormValue("email")
password := r.FormValue("password")

rows, err := DbConn.Query("SELECT userpassword FROM userinfo WHERE useremail=?", email)
defer rows.Close()
if err != nil {
	panic("SELECT ERROR")
}
  }

here how i initialize db in main.go

func init() {
tpl = template.Must(template.ParseGlob("templates/*"))
userStaff.InitDB("root:Yfehsp2203@tcp(127.0.0.1:3306)/golangdb")
  }

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