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 (

var db *gorm.DB

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

func InitDatabase() {
	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



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;


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.


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

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