Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Gorm automatically close the connection?

I have been using GORM for my application based on AWS lambda. I used gorm.Open() for every Handler function,

db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
        Logger: logger.Default.LogMode(logger.Info),
    })

so can someone help me confirm that does gorm.Open(...) automatically close the connection or not? Or I must use generic database interface bellow?

// Get generic database object sql.DB to use its functions
sqlDB, err := db.DB()

// Ping
sqlDB.Ping()

// Close
sqlDB.Close()

// Returns database statistics
sqlDB.Stats()
like image 761
Mark vu Avatar asked Sep 06 '25 03:09

Mark vu


1 Answers

A gorm.DB object is intended to be reused, like a sql.DB handle. You rarely have to explicitly close these objects. Just create it once and reuse it.

gorm.DB contains a sql.DB which uses a connection pool to manage the connections. If it is closed, it will stop accepting new queries, wait for running queries to finish and close all connections.

like image 170
gregor Avatar answered Sep 07 '25 23:09

gregor