15

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

Eklavya
  • 17,618
  • 4
  • 28
  • 57
Rohan Shukla
  • 533
  • 1
  • 4
  • 16

3 Answers3

24

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()
Aditya Kresna Permana
  • 11,869
  • 8
  • 42
  • 48
Alejandro Lorefice
  • 797
  • 1
  • 5
  • 18
8

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()
Max Base
  • 639
  • 1
  • 7
  • 15
Tho Quach
  • 1,347
  • 10
  • 26
2

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()
}()
Tsiao Wang
  • 51
  • 7