To create and manage database connection pools in Go, you can utilize a third-party library called database/sql
. Here's how you can proceed:
import (
"database/sql"
"log"
_ "github.com/go-sql-driver/mysql"
)
func createConnectionPool(dataSourceName string) (*sql.DB, error) {
db, err := sql.Open("mysql", dataSourceName)
if err != nil {
return nil, err
}
// Set the maximum number of idle connections in the pool
db.SetMaxIdleConns(10)
// Set the maximum number of open connections to the database
db.SetMaxOpenConns(100)
// Ping the database to verify the connection
if err := db.Ping(); err != nil {
return nil, err
}
return db, nil
}
Replace "github.com/go-sql-driver/mysql"
with the appropriate driver package for your database.
func main() {
dataSourceName := "username:password@tcp(localhost:3306)/database_name"
db, err := createConnectionPool(dataSourceName)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Use the connection pool for database queries
// ...
}
By setting a maximum number of idle connections and open connections, you can control the number of connections in the pool. Additionally, you can reuse existing connections, avoiding the need to establish a new one for each query, which can significantly improve performance.
Remember to close the connection pool by calling db.Close()
when you no longer need it.
Note: Connection pooling may differ depending on the database driver being used. The example above demonstrates connection pooling for MySQL, using the github.com/go-sql-driver/mysql
driver.