When working with MySQL databases in Go, it's crucial to choose a reliable and widely used driver. While there are multiple options available, the most recommended approach is to utilize drivers that implement the database/sql API.
Benefits of Database/SQL API:
Recommended Drivers:
MyMySQL:
Go-MySQL-Driver:
These drivers are known for their stability, high performance, and ability to handle large connection loads without interruptions.
Connection and Querying:
Once you've imported the appropriate driver, connect to your MySQL database as follows:
MyMySQL:
import "database/sql" func main() { // Assuming you have defined database, user, and password. con, err := sql.Open("mymysql", database+"/"+user+"/"+password) defer con.Close() }
Go-MySQL-Driver:
import "database/sql" func main() { // Assuming you have defined store as a type containing user, password, and database fields. con, err := sql.Open("mysql", store.user+":"+store.password+"@/"+store.database) defer con.Close() }
You can perform queries using the following syntax:
Select One 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)
Insert:
_, err = con.Exec("insert into tbl (id, mdpr, isok) values (?, ?, 1)", id, mdpr)
By following these recommendations, you'll benefit from the robustness and flexibility of Go's database/sql API.
The above is the detailed content of What's the Most Reliable Way to Connect to MySQL from Go?. For more information, please follow other related articles on the PHP Chinese website!