乐闻世界logo
搜索文章和话题

How do i close database instance in gorm 1.20.0

1个答案

1

When using GORM for database operations, it is a good practice to properly close the database connection when it is no longer needed. This helps release database resources and avoid database connection leaks. In GORM 1.20.0, you can achieve this by calling the Close method on the database connection.

Here is an example of closing a database instance using GORM:

go
package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" "log" ) func main() { // Initialize database connection db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { log.Fatalf("Database connection failed: %v", err) } // Your database operation logic... // Obtain the underlying `sql.DB` object to call the `Close` method sqlDB, err := db.DB() if err != nil { log.Fatalf("Failed to obtain underlying `sql.DB`: %v", err) } // Close the database connection err = sqlDB.Close() if err != nil { log.Fatalf("Failed to close database connection: %v", err) } }

In this example:

  1. We first create a database instance using gorm.Open.
  2. We obtain the underlying sql.DB object via the db.DB() method, which serves as the native database connection object.
  3. Finally, we call sqlDB.Close() to close the database connection.

Ensure these steps are executed when the application terminates or when the database connection is no longer needed to avoid memory leaks or other resource issues.

2024年7月31日 00:15 回复

你的答案