Connecting to MySQL from Go: A Comprehensive Guide
When accessing MySQL databases from Go applications, it's essential to choose a reliable and well-maintained driver. The database/sql API provides a standardized interface across different drivers, making it easier to switch between them.
Recommended Drivers
Two highly regarded drivers for connecting to MySQL from Go are:
Importing the Drivers
To import the chosen driver, include the following code in your Go file:
import ( "database/sql" _ "github.com/ziutek/mymysql/godrv" // For MyMySQL // or _ "github.com/go-sql-driver/mysql" // For Go-MySQL-Driver )
Connecting and Disconnecting
Using MyMySQL:
con, err := sql.Open("mymysql", database+"/"+user+"/"+password) defer con.Close()
Using Go-MySQL-Driver:
con, err := sql.Open("mysql", store.user+":"+store.password+"@/"+store.database) defer con.Close()
Basic CRUD Operations
Selecting a Single Row:
row := con.QueryRow("select mdpr, x, y, z from sometable where>
Selecting 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}) }
Inserting a Row:
_, err = con.Exec("insert into tbl (id, mdpr, isok) values (?, ?, 1)", id, mdpr)
Go's MySQL drivers provide a rich and efficient API for interacting with MySQL databases. By utilizing the database/sql package, you can abstract away the specific driver implementation, simplify code changes, and enhance your application's flexibility.
The above is the detailed content of How to Choose and Use the Best Go MySQL Driver for Database Interaction?. For more information, please follow other related articles on the PHP Chinese website!