In Go, managing database connections is made seamless with the database/sql package. This guide provides an in-depth overview of how to establish a MySQL connection and share it among your HTTP handlers.
The main() function is responsible for initializing your database connection. Here, you call sql.Open(), which returns a connection pool handle, not a single connection. This handle encapsulates the logic for providing connections as needed, ensuring efficient resource utilization.
db, err := sql.Open("mysql", "root:@/mydb?charset=utf8")
Once the connection pool is established, you can configure it to meet your application's needs. For instance, you can set the maximum number of idle connections in the pool:
db.SetMaxIdleConns(100)
To verify the availability of the database, you should perform a ping before proceeding:
err = db.Ping()
The key to sharing the connection lies in making the db variable a global variable accessible to both main() and your HTTP handlers. This ensures that all goroutines can utilize the same connection pool.
var db *sql.DB // global variable to share between main and HTTP handlers
Within your HTTP handlers, you can interact with the database using the shared connection. For example, to retrieve data from the "hello" table:
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) } }
The above is the detailed content of How to Share a MySQL Connection Across Go HTTP Handlers?. For more information, please follow other related articles on the PHP Chinese website!