How do I access mySQL database outside of the Init function in golang?

-1

Im trying to get data out of my database in golang. But i can't access it outside of the Init function. I run this Init function in the main:

package model

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)    
var Db *sql.DB

func InitDB() {
    Db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/test")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Connection Established")
    }
    defer Db.Close()

    fmt.Println(test(1))
}

func test(id int) string {
    var name string
    query := fmt.Sprintf("select username from user where user_id='%d';", 1)
    row := Db.QueryRow(query)
    row.Scan(&name)
    return name
}

When I put the code of test function inside the InitDB function it works perfectly fine. But this way I always get:

panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x1 addr=0x20 pc=0x6e96a8]

mysql
go
initialization
asked on Stack Overflow Jun 15, 2020 by Snessub • edited Jul 5, 2020 by Martijn Pieters

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0