Home >Backend Development >Golang >What's the Best Way to Connect to MySQL from Go?
Preferred Protocol for Connecting to MySQL from Go
When seeking a dependable method to establish connections with MySQL databases from Go, numerous libraries emerge as potential solutions. However, assessing the maturity and ongoing maintenance of these libraries remains a challenge. For those seeking a straightforward and widely adopted approach, the following recommendations are provided.
Recommended Libraries Implementing the database/sql API
The database/sql API serves as a preferred interface for working with SQL databases in Go. This API provides:
Two fast and reliable drivers implementing this API are:
These drivers are proven to handle high-volume connections reliably, delivering consistent performance in production environments.
Sample Usage with MyMySQL
import ( "database/sql" _ "github.com/ziutek/mymysql/godrv" ) func main() { // Username, password, and database details are placeholders db, err := sql.Open("mymysql", "database/user/password") if err != nil { // Handle error } // Perform database operations db.Close() }
Sample Usage with Go-MySQL-Driver
import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) func main() { // Username, password, and database details are placeholders db, err := sql.Open("mysql", "user:password@/database") if err != nil { // Handle error } // Perform database operations db.Close() }
Database Operations
The following operations demonstrate working with MySQL in Go:
var cb SomeThing err := con.QueryRow("select ...").Scan(&cb.Mdpr, &cb.X, &cb.Y, &cb.Z)
var items []*SomeStruct for rows.Next() { err = rows.Scan(&ida, &idb) items = append(items, &SomeStruct{ida, idb}) }
_, err = con.Exec("insert into ...")
MySQL integration in Go is highly efficient and reliable, offering stable operation for extended periods. The flexibility of the database/sql API enables seamless driver switching without disrupting application logic.
The above is the detailed content of What's the Best Way to Connect to MySQL from Go?. For more information, please follow other related articles on the PHP Chinese website!