如何使用Go和go-sql-driver连接到mysql服务器?

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

How do I connect to mysql server with Go and go-sql-driver?

问题

我正在按照这里这里的教程进行操作,但是我无法连接到安装的MySQL中的test数据库。我可以通过命令行连接到MySQL。我错过了什么?当我运行下面的代码时,我得到了“无法ping”的错误:

package main

import (
	"fmt"
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	db, err := sql.Open("mysql", "/test")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	
	err = db.Ping()
	if err != nil {
		fmt.Println("cannot ping")
		return
	} 
}
英文:

I am following the tutorials here and here but I am unable to connect to the test database that came with mySQL installation. I can connect to mySql through the command line. What am I missing? When I run the code below I get the error "cannot ping":

package main

import (
	"fmt"
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	db, err := sql.Open("mysql", "/test")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	
	err = db.Ping()
	if err != nil {
		fmt.Println("cannot ping")
		return
	} 
}

答案1

得分: 2

例如,将你的MySQL用户名和密码替换为userpassword

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	db, err := sql.Open("mysql", "user:password@/test")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	err = db.Ping()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Ping")
}

输出:

Ping
英文:

For example, substitute your MySQL user name and password for the words user and password,

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	db, err := sql.Open("mysql", "user:password@/test")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	err = db.Ping()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Ping")
}

Output:

Ping

huangapple
  • 本文由 发表于 2013年7月10日 07:53:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/17560232.html
匿名

发表评论

匿名网友

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

确定