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


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 (

    _ ""
var Db *sql.DB

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


func test(id int) string {
    var name string
    query := fmt.Sprintf("select username from user where user_id='%d';", 1)
    row := Db.QueryRow(query)
    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]

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