问题描述
我正在寻找一种可靠的解决方案来从 Go 连接到 MySQL 数据库.我已经看到了一些库,但很难确定完整性和当前维护的不同状态.我没有复杂的需求,但我想知道人们依赖什么,或者连接 MySQL 的最标准的解决方案是什么.
I am looking for a reliable solution to connect to a MySQL database from Go. I've seen some libraries around but it is difficult to determine the different states of completeness and current maintenance. I don't have complicated needs, but I'd like to know what people are relying on, or what's the most standard solution to connect to MySQL.
推荐答案
有一些驱动程序可用,但您应该只考虑那些实现 数据库/sql API 为
A few drivers are available but you should only consider those that implement the database/sql API as
- 它提供了一种简洁高效的语法,
- 它确保您以后可以在不更改代码的情况下更改驱动程序,除了导入和连接.
有两个快速可靠的 MySQL 驱动程序可用:
Two fast and reliable drivers are available for MySQL :
- MyMySQL
- Go-MySQL-Driver
我已经在生产中使用了它们,程序运行了数月,连接数以百万计没有失败.
I've used both of them in production, programs are running for months with connection numbers in the millions without failure.
其他 SQL 数据库驱动程序列于 go-wiki.
Other SQL database drivers are listed on go-wiki.
使用 MyMySQL 时导入:
import (
"database/sql"
_ "github.com/ziutek/mymysql/godrv"
)
使用 Go-MySQL-Driver 时导入:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
使用 MyMySQL 连接和关闭:
con, err := sql.Open("mymysql", database+"/"+user+"/"+password)
defer con.Close()
// here you can use the connection, it will be closed when function returns
使用 Go-MySQL-Driver 连接和关闭:
con, err := sql.Open("mysql", store.user+":"+store.password+"@/"+store.database)
defer con.Close()
选择一行:
row := con.QueryRow("select mdpr, x, y, z from sometable where id=?", id)
cb := new(SomeThing)
err := row.Scan(&cb.Mdpr, &cb.X, &cb.Y, &cb.Z)
选择多行并用结果构建一个数组:
rows, err := con.Query("select a, b from item where p1=? and p2=?", p1, p2)
if err != nil { /* error handling *