如何使用Go连接到MySQL?

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

How to connect to mysql with go?

问题

我一直在尝试使用go连接mysql,但似乎无法成功。我只是想从表中获取一个值,将其设置为变量并打印出来。我可能只是缺少一些显而易见的东西。

这是来自名为bankdata的数据库的内容:

mysql> select * from accounts ;
+----+----------+-----------------+----------+---------+
| id | username | email | facebook | twitter |
+----+----------+-----------------+----------+---------+
| 1 | user1 | email1@mail.com | userfb1 | NULL |
| 2 | user2 | email2@mail.com | NULL | NULL |
| 3 | user3 | email3@mail.com | NULL | NULL |
+----+----------+-----------------+----------+---------+

我使用了两个驱动程序,但我似乎无法理解两者的问题所在。

使用go-sql-driver

package main

import (
	"database/sql"
	_ "github.com/Go-SQL-Driver/MySQL"
	"log"
)

const (
	DB_HOST = "tcp(127.0.0.1:3306)"
	DB_NAME = "bankdata"
	DB_USER = /*"root"*/ "bankadmin"
	DB_PASS = /*""*/ "1234"
)

func main() {
	dsn := DB_USER + ":" + DB_PASS + "@" + DB_HOST + "/" + DB_NAME + "?charset=utf8"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	var str string
	q := "select username from bankadmin.accounts where id = 1"
	err = db.QueryRow(q).Scan(&str)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(str)
}

这返回:

D:\_>go run dbtest.go
2013/03/29 13:14:11 Error 1045: Access denied for user 'bankadmin'@'localhost'
(using password: YES)
exit status 1

密码实际上是正确的,对于root用户和bankadmin用户都是如此,并且mysql在端口3306上运行。但是,如果我将DB_HOST更改为"tcp(127.0.0.1:3000)"或将127.0.0.1更改为localhost,它会给我相同的错误。

使用mymysql驱动程序

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/ziutek/mymysql/godrv"
	"log"
	"strconv"
)

const (
	DB_HOST = "tcp(127.0.0.1:3306)"
	DB_NAME = "bankdata"
	DB_USER = "bankadmin"
	DB_PASS = "1234"
)

type User struct {
	Id       int
	Username string
	Email    string
	Facebook string
}

func OpenDB() *sql.DB {
	db, err := sql.Open("mymysql", fmt.Sprintf("%s/%s/%s", DB_NAME, DB_USER, DB_PASS))
	if err != nil {
		panic(err)
		log.Fatal(err)
	}
	return db
}

func UserById(id int) *User {
	db := OpenDB()
	defer db.Close()
	row := db.QueryRow("SELECT id, username, email FROM accounts WHERE id=?", id)
	user := new(User)
	row.Scan(&user.Id, &user.Username, &user.Email, &user.Facebook)
	return user
}

func main() {
	db := OpenDB()
	defer db.Close()
	row := db.QueryRow("SELECT id, username, email, facebook FROM accounts WHERE id=2")
	user := new(User)
	row.Scan(&user.Id, &user.Username, &user.Email, &user.Facebook)
	fmt.Println("id    : " + strconv.Itoa(user.Id) + "\nname  : " + user.Username + "\nemail : \n" + user.Email)
}

这返回:

D:\_>go run dbtest.go
id    : 0
name  :
email :

看起来id和字符串都是空的,就像从row.Scan函数中从未接收到任何值一样。我不知道如何确保它们连接,即使它们没有给我与之前的驱动程序相同的错误。

哦,我使用的是Windows 7,带有WAMP的MySQL 5.5.8。

如果我在这篇文章中犯了任何错误,请原谅我。这是我第一篇帖子。

英文:

I have been trying to connect mysql with go, but i can seem to succeed. I'm just trying to get a value from table and set it to variable and print it. What i'm missing maybe just something obvious

this is from the database called bankdata

mysql> select * from accounts ;
+----+----------+-----------------+----------+---------+
| id | username | email           | facebook | twitter |
+----+----------+-----------------+----------+---------+
|  1 | user1    | email1@mail.com | userfb1  | NULL    |
|  2 | user2    | email2@mail.com | NULL     | NULL    |
|  3 | user3    | email3@mail.com | NULL     | NULL    |
+----+----------+-----------------+----------+---------+

there's two drivers that i used, and i can seem to understand what wrong with both of them

using go-sql-driver

package main
import (
"database/sql"
_ "github.com/Go-SQL-Driver/MySQL"
"log"
)
const (
DB_HOST = "tcp(127.0.0.1:3306)"
DB_NAME = "bankdata"
DB_USER = /*"root"*/ "bankadmin"
DB_PASS = /*""*/ "1234"
)
func main() {
dsn := DB_USER + ":" + DB_PASS + "@" + DB_HOST + "/" + DB_NAME + "?charset=utf8"
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
var str string
q := "select username from bankadmin.accounts where id = 1"
err = db.QueryRow(q).Scan(&str)
if err != nil {
log.Fatal(err)
}
log.Println(str)
}

this returns

D:\_>go run dbtest.go
2013/03/29 13:14:11 Error 1045: Access denied for user 'bankadmin'@'localhost'
(using password: YES)
exit status 1

the password is actually right, for the both user root and bankadmin, and the mysql in running in port 3306. But then again, if i change the DB_HOST to "tcp(127.0.0.1:3000)" or change the 127.0.0.1 to localhost, it gave me the same error.

using mymysql driver

package main
import (
"database/sql"
"fmt"
_ "github.com/ziutek/mymysql/godrv"
"log"
"strconv"
)
const (
DB_HOST = "tcp(127.0.0.1:3306)"
DB_NAME = "bankdata"
DB_USER = "bankadmin"
DB_PASS = "1234"
)
type User struct {
Id       int    
Username string 
Email    string 
Facebook string
}
func OpenDB() *sql.DB {
db, err := sql.Open("mymysql", fmt.Sprintf("%s/%s/%s", DB_NAME, DB_USER, DB_PASS))
if err != nil {
panic(err)
log.Fatal(err)
}
return db
}
func UserById(id int) *User {
db := OpenDB()
defer db.Close()
row := db.QueryRow("SELECT id, username, email FROM accounts WHERE id=?", id)
user := new(User)
row.Scan(&user.Id, &user.Username, &user.Email, &user.Facebook)
return user
}
func main() {
db := OpenDB()
defer db.Close()
row := db.QueryRow("SELECT id, username, email, facebook FROM accounts WHERE id=2")
user := new(User)
row.Scan(&user.Id, &user.Username, &user.Email, &user.Facebook)
fmt.Println("id    : " + strconv.Itoa(user.Id) + "\nname  : " + user.Username + "\nemail : \n" + user.Email)
}

this returns:

D:\_>go run dbtest.go
id    : 0
name  :
email :

it looks like both the id and the strings is empty, like it's never received any values from row.Scan function. And i don't know how to make sure that they are connected even though they didn't give me the same error as the previous driver

Oh, and i'm using Windows 7, MySQL 5.5.8 that comes with WAMP.

If i made any mistake in this post, pardon me. This is my first post.

答案1

得分: 2

问题不在于你的Go代码,问题在于你的MySQL配置。你可能有正确的用户名和密码,但你可能没有授权该用户使用TCP连接到数据库。

英文:

The problem isn't your go code the problem is you mysql configuration. You may have the right username and password but you probably haven't authorized that user to connect to the database using tcp.

答案2

得分: 1

如@Jeremy wall所提到的,问题出在连接字符串上。我使用的用户名是错误的。要配置设置,按照以下步骤进行:

  1. 进入“服务器”选项
  2. 选择“管理服务器连接”
  3. 选择“连接”部分
  4. 在密码部分点击“存储在钥匙串”按钮,并输入新密码

设置完成后,尝试点击“测试连接”按钮。当我尝试从GO程序访问数据库时,它对我有效。

英文:

如何使用Go连接到MySQL?

As mentioned by @Jeremy wall, the problem was with the connection string. The user name i used is wrong. To configure the settings,

  1. Go to "Server" option
  2. Select Manage Server Connections
  3. select Connections section
  4. Click store in keychain button in password section and enter new password

you are all set. now try the test connection button. It worked for me when i tried to access the db from GO program.

huangapple
  • 本文由 发表于 2013年3月29日 14:29:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/15698479.html
匿名

发表评论

匿名网友

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

确定