What#39;s the recommended way to connect to MySQL from Go?(从 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 *
本文标题为:从 Go 连接到 MySQL 的推荐方法是什么?


- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- SQL 临时表问题 2022-01-01