Home > Backend Development > Golang > How to Share a MySQL Connection Among HTTP Goroutines in Go?

How to Share a MySQL Connection Among HTTP Goroutines in Go?

Mary-Kate Olsen
Release: 2024-11-18 06:14:02
Original
386 people have browsed it

How to Share a MySQL Connection Among HTTP Goroutines in Go?

Sharing MySQL Connection among HTTP Goroutines in Go

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.

Overview

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.

Sharing the Connection

To share the connection between main() and HTTP handlers, declare a global db variable:

var db *sql.DB
Copy after login

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())
}
Copy after login

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)
    }
}
Copy after login

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template