Home >Backend Development >Golang >How do I share a MySQL connection across multiple HTTP goroutines in Go?
When working with HTTP goroutines in Go, it's essential to optimize performance by sharing database connections. This article demonstrates how to establish and share a MySQL connection among multiple HTTP handlers.
In Go, the database/sql package handles connection pooling automatically. When calling sql.Open(...), a connection pool is created rather than a single connection. This means that the database/sql package will automatically obtain a connection from the pool if all connections are already in use.
To share a MySQL connection in your HTTP goroutines, follow these steps:
Initialize the Database Connection:
Example:
db, err := sql.Open("mysql", "root:@/mydb?charset=utf8") if err != nil { log.Fatalf("Error opening database: %v", err) }
Configure Connection Pooling:
Share the Connection Handle:
Example:
var db *sql.DB
Check Database Connection:
Example:
err = db.Ping() if err != nil { log.Fatalf("Error opening database connection: %s", err.Error()) }
Use Connection in HTTP Handlers:
Example:
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 efficiently share a MySQL connection across multiple HTTP goroutines without compromising performance.
The above is the detailed content of How do I share a MySQL connection across multiple HTTP goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!