In Go, managing database connections in concurrency can be a bit confusing. This article explores how to effectively share a MySQL connection among multiple HTTP goroutines.
When using the database/sql package in Go, calling sql.Open() doesn't establish an immediate database connection. Instead, it creates a connection pool, a collection of connections managed by the package. The package automatically handles the pooling, opening new connections when needed.
To share the connection between main() and HTTP handlers, declare a global db variable:
var db *sql.DB
In main(), initialize the connection pool:
db, err := sql.Open("mysql", "root@unix(/tmp/mysql.sock)/mydb") if err != nil { log.Fatalf("Error on initializing database connection: %s", err.Error()) } db.SetMaxIdleConns(100) err = db.Ping() // Opens a connection if necessary if err != nil { log.Fatalf("Error on opening database connection: %s", err.Error()) }
HTTP handlers can then access the shared database connection:
func HomeHandler(w http.ResponseWriter, r *http.Request) { var msg string err := db.QueryRow("SELECT msg FROM hello WHERE page=?", "home").Scan(&msg) if err != nil { fmt.Fprintf(w, "Database Error!") } else { fmt.Fprintf(w, msg) } }
By following these steps, you can effectively share a MySQL connection among multiple HTTP goroutines in Go, ensuring efficient database access without unnecessary overhead.
The above is the detailed content of How to Share a MySQL Connection Among HTTP Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!