从 Go 连接到 MySQL 的推荐方法是什么?
我正在寻找一种可靠的解决方案来从 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 */}
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})
}
插入:
_, err = con.Exec("insert into tbl (id, mdpr, isok) values (?, ?, 1)", id, mdpr)
您会发现在 Go 中使用 MySQL 是一种愉快的体验:我从未遇到问题,我的服务器运行数月没有错误或泄漏.大多数函数只采用可变数量的参数这一事实减轻了许多语言中乏味的任务.
You'll see that working in Go with MySQL is a delightful experience : I never had a problem, my servers run for months without errors or leaks. The fact that most functions simply take a variable number of arguments lighten a task which is tedious in many languages.
请注意,如果将来您需要使用另一个 MySQL 驱动程序,您只需更改一个 go 文件中的两行:执行导入的行和打开连接的行.
Note that if, in the future, you need to use another MySQL driver, you'll just have to change two lines in one go file : the line doing the import and the line opening the connection.
相关文章