Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i close database instance in gorm 1.20.0

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

like image 649
Rohan Shukla Avatar asked Sep 09 '20 16:09

Rohan Shukla


People also ask

How do I close Gorm DB?

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.

What is * Gorm DB?

GORM provides the method DB which returns a generic database interface *sql.DB from the current *gorm.DB. // Get generic database object sql.DB to use its functions. sqlDB, err := db.DB()


Video Answer


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()
like image 54
A.Lorefice Avatar answered Oct 18 '22 21:10

A.Lorefice


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()
like image 8
Tho Quach Avatar answered Oct 18 '22 20:10

Tho Quach