Connecting to mysql database with go

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

Connecting to mysql database with go

问题

我正在尝试与我的MySQL服务器建立基本连接,但似乎无法实际连接。我知道凭据是有效的,并且具有所需的所有权限,但由于某种原因它们始终被拒绝。

package main

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

func main() {
	db, err:= sql.Open("mysql", "user:pass@tcp(localhost:3306)/scf")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	
	q, err := db.Prepare("SELECT * from logins limit 5")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	rows, err := q.Query()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	
	i := 0
	
	for rows.Next() {
		i++
		var title string
		err = rows.Scan( &title )
		fmt.Printf("Title: %s \n", title)
	}
	
	db.Close()
	
}

编辑:

显然我忘记包含错误信息:

dial tcp 127.0.0.1:3306: connection refused
exit status 1
英文:

I'm trying to get a basic connect to my mysql server, but I can't seem to get it to actually connect. I know the credentials are valid and have all the permissions they need, but for some reason they're consistently rejected.

package main

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

func main() {
	db, err:= sql.Open("mysql", "user:pass@tcp(localhost:3306)/scf")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	
	q, err := db.Prepare("SELECT * from logins limit 5")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	rows, err := q.Query()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	
	i := 0
	
	for rows.Next() {
		i++
		var title string
		err = rows.Scan( &title )
		fmt.Printf("Title: %s \n", title)
	}
	
	db.Close()
	
}

Edit:

Apparently I forgot to include the error:

dial tcp 127.0.0.1:3306: connection refused
exit status 1

答案1

得分: 3

连接被拒绝通常意味着端口未打开或被防火墙阻止。请检查以下几点:

  • MySQL(在本地主机上)是否正在运行?它是否在3306端口上?
  • 如果你使用的是Windows、Mac或Linux系统,是否有防火墙可能阻止了3306端口?
  • 如果你使用的是Linux系统,是否启用了SELinux,它可能会阻止3306端口的连接?
英文:

connection refused generally means the port isn't open or is being blocked by a firewall. A couple things to check:

  • Is MySQL (on localhost) running? Is it on port 3306?
  • If you're on Windows, Mac or Linux, is there a firewall that might be blocking port 3306?
  • If you're on Linux, is SELinux enabled that might be blocking port 3306?

答案2

得分: 0

我遇到了类似的问题。我发现在Mac上端口是不同的。我在my.cnf中找不到它,但是端口是在运行时设置的,你可以使用以下命令查看:

ps ax | grep mysql
英文:

I faced a similar issue. I found out port was different on Mac. I Couldn't find it in my.cnf but the port was set during runtime which you can see using

ps ax | grep mysql

huangapple
  • 本文由 发表于 2013年9月12日 07:39:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/18753066.html
匿名

发表评论

匿名网友

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

确定