How do i close database instance in gorm 1.20.0

Viewed 14418

As i have not found in Close() function with *gorm instance, any help would be appreciated

dbURI := fmt.Sprintf("user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=%s",
    "username", "password", "dbname", "5432", "disable", "Asia/Kolkata")
fmt.Println(dbURI)
connection, err := gorm.Open(postgres.Open(dbURI), &gorm.Config{})

if err != nil {
    fmt.Println("Error connecting database")
    panic(err.Error())
} else {
    fmt.Println("Connected to database")
}

Note: connection.Close() is not available for GORM 1.20.0

2 Answers

Jinzhu decided to eliminate the Close() method on version 1.20 because GORM supports connection pooling, so the correct use would be to open a connection and share it within your application.

If your specific use-case still requires to use the Close() method, GORM provides the method DB that returns a db generic_interface where you can use it.

For the example

sqlDB, err := db.DB()

// Close
sqlDB.Close()

I think you can use below codes to close your database connection:

sqlDB, err := connection.DB()
if err != nil {
    log.Fatalln(err)
}
defer sqlDB.Close()
Related