How do i close database instance in gorm 1.20.0

30.1k Views Asked by At

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

3

There are 3 best solutions below

3
On

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()
1
On

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()
0
On

Gorm v2 provides a method to close the db connection.

Here is an example:

db, err := gorm.Open(sqlite.Open(dbFile), &gorm.Config{
    Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
    t.Error(err)
}

defer func() {
    dbInstance, _ := db.DB()
    _ = dbInstance.Close()
}()