Cant close DB Connection with db.Close()

Hello guys,

I am trying to setup a database connection and want at the end a defer db.DB.Close() or db.Close() both doesnt work for me

At my following Code it tells me: Unresolved reference ‘Close’.

Can someone Help me maybe with that? That would be awesome :slight_smile:

package database

import (
	"github.com/joho/godotenv"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"log"
	"os"
)

var db *gorm.DB

func LoadingEnv() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading EnvFile")
	}
}

func InitDatabase() {
	LoadingEnv()
	dbConnStr := os.Getenv("DB_CONN_STR")
	if dbConnStr == "" {
		log.Fatal("Wrong ConnectionString")
	}
	var err error
	db, err = gorm.Open(postgres.Open(dbConnStr), &gorm.Config{})
	if err != nil {
		log.Fatal("Error opening DB connection")
	}
	defer db.DB.Close() // Access the underlying sql.DB instance and call Close
}

Cheers

Zoxyren

Hello there. *gorm.DB does not have DB as the struct field. It has DB() method which returns underlying connection and error. This way you can get access to the connection to close it.

But also pay attention, that sql package do it on it’s own:

The sql package creates and frees connections automatically;

2 Likes

In previous versions of Gorm they had a DB.Close function but it was removed in v1.20:

It’s likely you were looking at examples from older versions of Gorm. If you look at the implementation, they were just calling Close on the underlying sql/DB connection pool:

So you could change your code to the following if you really need to close the pool:

defer func() {
    // Ignoring errors since there/s not much we can do at this point
    sqlDB, _ := db.DB()
    _ = sqlDB.Close()
}()

… BUT you probably don’t need to as @lemarkar mentioned. Here’s from another section in the docs on sql.Open (emphasis mine):

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

2 Likes

Thanks both to you, you helped me really much with it :slight_smile:

And sorry for the delayed response.

Cheers and happy weekend all.

  • Refer to the specific library or framework you’re using for database interaction. The method to close the connection might be different than db.Close(). For instance, in Gorm v2 with Postgres, there’s no db.Close() method, but DB() to get the underlying connection.
1 Like