How do I set connection pool limits using GORM?

Setting connection pool limits in GORM is an essential aspect of managing database connections efficiently. GORM provides a simple way to configure connection pooling by setting specific parameters such as the maximum number of connections and the maximum idle connections. This ensures optimal performance of your application and helps prevent database overload.

Here’s a basic example of how to set connection pool limits using GORM in a Go application:

package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" "time" ) func main() { // Set connection pool limits db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) if err != nil { panic("failed to connect database") } sqlDB, err := db.DB() if err != nil { panic("failed to get database connection") } // Set connection pool settings sqlDB.SetMaxIdleConns(10) // Set the maximum number of idle connections sqlDB.SetMaxOpenConns(100) // Set the maximum number of open connections sqlDB.SetConnMaxLifetime(time.Hour) // Set the maximum connection lifetime // Your application logic here... }

Go GORM connection pool database connections Go ORM database management