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:
gopackage 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:
- We first create a database instance using
gorm.Open. - We obtain the underlying
sql.DBobject via thedb.DB()method, which serves as the native database connection object. - 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 回复