什么是从Go连接到MySQL的推荐方法?

huangapple go评论95阅读模式
英文:

What's the recommended way to connect to MySQL from Go?

问题

我正在寻找一个可靠的解决方案,用于从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 complex needs, but I'd like to know what people are relying on or the most standard solution to connect to MySQL.

答案1

得分: 267

<!-- language: lang-go -->

有几个驱动程序可用,但您应该只考虑那些实现了database/sql API的驱动程序,因为

  • 它提供了清晰高效的语法,
  • 它确保您以后可以在不更改代码的情况下更改驱动程序,除了导入和连接。

MySQL有两个快速可靠的驱动程序可用:

我在生产中使用了这两个驱动程序,程序运行了数月,连接数达到了数百万,没有出现故障。

其他SQL数据库驱动程序在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()
// 在这里您可以使用连接,在函数返回时它将被关闭

使用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 { /* 错误处理 */}
items := make([]*SomeStruct, 0, 10)
var ida, idb uint
for rows.Next() {
    err = rows.Scan(&ida, &idb)
    if err != nil { /* 错误处理 */}
    items = append(items, &SomeStruct{ida, idb})
}

插入:

_, err = con.Exec("insert into tbl (id, mdpr, isok) values (?, ?, 1)", id, mdpr)

您会发现使用Go和MySQL是一种愉快的体验:我从未遇到过问题,我的服务器运行数月没有错误或泄漏。大多数函数只需要一个可变数量的参数,这简化了在许多语言中繁琐的任务。

请注意,如果将来需要使用另一个MySQL驱动程序,您只需更改一个go文件中的两行代码:导入代码和打开连接的代码。

英文:

<!-- language: lang-go -->

A few drivers are available but you should only consider those that implement the database/sql API as

  • it provides a clean and efficient syntax,
  • it ensures you can later change the driver without changing your code, apart the import and connection.

Two fast and reliable drivers are available for MySQL :

I've used both of them in production, programs are running for months with connection numbers in the millions without failure.

Other SQL database drivers are listed on go-wiki.

Import when using MyMySQL :

import (
	&quot;database/sql&quot;
	_ &quot;github.com/ziutek/mymysql/godrv&quot;
)

Import when using Go-MySQL-Driver :

import (
	&quot;database/sql&quot;
	_ &quot;github.com/go-sql-driver/mysql&quot;
)

Connecting and closing using MyMySQL :

con, err := sql.Open(&quot;mymysql&quot;, database+&quot;/&quot;+user+&quot;/&quot;+password)
defer con.Close()
// here you can use the connection, it will be closed when function returns

Connecting and closing using Go-MySQL-Driver :

con, err := sql.Open(&quot;mysql&quot;, store.user+&quot;:&quot;+store.password+&quot;@/&quot;+store.database)
defer con.Close()

Select one row :

row := con.QueryRow(&quot;select mdpr, x, y, z from sometable where id=?&quot;, id)
cb := new(SomeThing)
err := row.Scan(&amp;cb.Mdpr, &amp;cb.X, &amp;cb.Y, &amp;cb.Z)

Select multiple rows and build an array with results :

rows, err := con.Query(&quot;select a, b from item where p1=? and p2=?&quot;, p1, p2)
if err != nil { /* error handling */}
items := make([]*SomeStruct, 0, 10)
var ida, idb uint
for rows.Next() {
    err = rows.Scan(&amp;ida, &amp;idb)
    if err != nil { /* error handling */}
    items = append(items, &amp;SomeStruct{ida, idb})
}

Insert :

_, err = con.Exec(&quot;insert into tbl (id, mdpr, isok) values (?, ?, 1)&quot;, id, mdpr)

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.

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.

答案2

得分: 2

few things to take note
the select 1 row example :

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)

there is a missing row.Next() in this example. it need to call the row.Next() to grab the first row returned.

also there is some inflexibility to the library which in some way try to promote data minimalism. if you try to select columns that is not Scan it will throw errors (not just warnings)

英文:

few things to take note
the select 1 row example :

row := con.QueryRow(&quot;select mdpr, x, y, z from sometable where id=?&quot;,id) 
cb := new(SomeThing) 
err := row.Scan(&amp;cb.Mdpr, &amp;cb.X, &amp;cb.Y, &amp;cb.Z)

there is a missing row.Next() in this example. it need to call the row.Next() to grab the first row returned.

also there is some inflexibility to the library which in some way try to promote data minimalism. if you try to select columns that is not Scan it will throw errors (not just warnings)

答案3

得分: 0

我认为Gorm是连接到Mysql或PostgreSQL的完美方式。

英文:

I see the Gorm as a perfect way to connect to Mysql or PostgreSQL.

huangapple
  • 本文由 发表于 2012年7月6日 07:00:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/11353679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定