0

Trying to create a simple api. getting the following error:

Status: dial tcp [::1]:3306: connect: connection refused panic: sql: database is closed

I believe the db is running. I can see the tables using mysql -uroot.

here is my main.go file:

package main
import (
    "fmt"
    "github.com/jinzhu/gorm"
    "resource-api/Config"
    "resource-api/Models"
    "resource-api/Routes"
)

var err error

func main() {
    Config.DB, err = gorm.Open("mysql", Config.DbURL(Config.BuildDBConfig()))
    if err != nil {
        fmt.Println("Status:", err)
    }
    defer Config.DB.Close()
    Config.DB.AutoMigrate(&Models.Client{})
    r := Routes.SetupRouter()
    //running
    r.Run()
}

here is

Config/Database.go:

//

package Config

import (
    "fmt"

    "github.com/jinzhu/gorm"
)

var DB *gorm.DB

// DBConfig represents db configuration
type DBConfig struct {
    Host string
    Port int
    User string
    DBName string
    Password string
}

func BuildDBConfig() *DBConfig {
    dbConfig := DBConfig{
        Host: "localhost",
        Port: 3306,
        User: "root",
        Password: "",
        DBName: "resourcesdb",
    }
    return &dbConfig
}

func DbURL(dbConfig *DBConfig) string {
    return fmt.Sprintf(
        "%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
        dbConfig.User,
        dbConfig.Password,
        dbConfig.Host,
        dbConfig.Port,
        dbConfig.DBName,
        )
}
user2799827
  • 1,077
  • 3
  • 18
  • 54
  • You seem to be missing the driver import. For an example on how to connect see: https://gorm.io/docs/connecting_to_the_database.html – mkopriva Aug 28 '21 at 02:32
  • first thing you missed the driver import. anyway the error seems like an issue with msql server, try command `mysql -h localhost -P 3306 -u root -p` to ensure it is running on localhost port. – arunjos007 Aug 28 '21 at 04:59
  • arunjos007 ran your command. response is: ~ > mysql -h localhost -P 3306 -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 9 Server version: 8.0.26 Homebrew Copyright (c) 2000, 2021, Oracle and/or its affiliates. – user2799827 Aug 28 '21 at 06:53
  • @user2799827 Just try below code with your cred, https://play.golang.org/p/T3rr6YbMIfJ – arunjos007 Aug 28 '21 at 08:02
  • new error: Error on open DB connection dial tcp 127.0.0.1:3306: connect: connection refusedSuccessfully opened DB connection &{RWMutex:{w:{state:0 sema:0} writerSem:0 readerSem:0 readerCount:0 readerWait:0} Value: Error: RowsAffected:0 db:0xc00023dad0 blockGlobalUpdate:false logMode:0 logger:{LogWriter:0xc0001a7e50} search: values:{mu:{state:0 sema:0} read:{v:} dirty:map[] misses:0} parent:0xc00023dba0 callbacks:0x1949920 dialect:0xc0001210c8 singularTable:false nowFuncOverride:}panic: sql: database is closed – user2799827 Aug 28 '21 at 08:29
  • just check this, seems it will resolve your new error https://stackoverflow.com/questions/52504318/unable-to-connect-to-mysql-server-with-go-and-docker-dial-tcp-127-0-0-13306 – arunjos007 Aug 28 '21 at 09:05
  • Changing the drivers worked. Thanks all. Can post answer with working code if people want it. – user2799827 Aug 28 '21 at 13:18

1 Answers1

-1

I'm guessing Routes::run() runs a separate thread for the router in your API?

That means the main() function terminates, so Config.DB.Close() fires right after you've just started that separate thread that was intending to use the open connection. By the time it gets around to using it, it's already closed.

As a general rule, you probably don't need to explicitly call DB.Close() in most cases; Go will clean up for you when it's done. If for some reason you do need to do that in this case, you'll want the separate thread to handle the closing when it's done, not put it in main(). So I'd try removing that line first, and see if that works for you.

George
  • 140
  • 6