Connecting to MySQL from Go is made easy with the appropriate driver. Among the available options, those that adhere to the database/sql API are recommended for their:
Two fast and reliable drivers stand out for MySQL connection:
Production-tested experience confirms their stability and performance.
MyMySQL:
con, err := sql.Open("mymysql", database+"/"+user+"/"+password) defer con.Close()
Go-MySQL-Driver:
con, err := sql.Open("mysql", store.user+":"+store.password+"@/"+store.database) defer con.Close()
Select a single row:
row := con.QueryRow("select mdpr, x, y, z from sometable where>
Select multiple rows:
rows, err := con.Query("select a, b from item where p1=? and p2=?", p1, p2) if err != nil { /* error handling */} items := make([]*SomeStruct, 0, 10) var ida, idb uint for rows.Next() { err = rows.Scan(&ida, &idb) if err != nil { /* error handling */} items = append(items, &SomeStruct{ida, idb}) }
Insert operation:
_, err = con.Exec("insert into tbl (id, mdpr, isok) values (?, ?, 1)", id, mdpr)
Using the database/sql API in Go for MySQL connectivity offers several benefits:
With reliable drivers and a powerful API, connecting to MySQL in Go is a seamless experience.
The above is the detailed content of What's the Best Way to Connect to MySQL from Go Using the `database/sql` API?. For more information, please follow other related articles on the PHP Chinese website!