How do I open and pool connections using GORM?

GORM is a powerful ORM (Object Relational Mapping) library for Golang, which simplifies the process of handling database connections and operations. This guide will demonstrate how to open and pool connections using GORM, ensuring efficient database interactions in your Go applications.
Go, GORM, database connections, connection pooling, Golang ORM

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "log"
)

func main() {
    // Define the connection string
    dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"

    // Open a new database connection
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        log.Fatal("failed to connect database: ", err)
    }

    // Configure connection pooling
    sqlDB, err := db.DB()
    if err != nil {
        log.Fatal("failed to get generic database: ", err)
    }

    // Set the maximum number of connections in the idle connection pool
    sqlDB.SetMaxIdleConns(10)

    // Set the maximum number of open connections to the database
    sqlDB.SetMaxOpenConns(100)

    // Set the maximum lifetime of a connection
    sqlDB.SetConnMaxLifetime(60 * time.Minute)

    // Continue with your application logic...
}

Go GORM database connections connection pooling Golang ORM