When connecting to mysql database mysql 5.7
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
db, err := sql.Open("mysql", "root:xxx@tcp(localhost:3306)/mydb")
err = db.Ping()
Error
Error 1130: Host '127.0.0.1' is not allowed to connect to this MySQL server
But when connecting via command line no errors?
mysql -u root -pxxx -h localhost
Have also connected to phpmyadmin with the same user/pass without issues from localhost
update
How now tried to connect to mysql 8 and it works. How to connect to mysql 5.7?
In the docs it says it supports mysql 5.6+
2
Answers
Maybe there is an error with the sqlx package. Try using the sql package like this:
Normally using the hostname "localhost" is not 127.0.0.1. It’s treated specially, causing MySQL clients to use the UNIX domain socket instead of TCP.
This also applies to GRANT. So if you grant to
myuser@localhost
, it means that user has access only via UNIX socket. If you want a user to be able to connect locally but using TCP, you must grant to[email protected]
or some other wildcard pattern that covers that IP address.In a way,
myuser@localhost
and[email protected]
are really different users. They can even have distinct passwords and distinct privileges.However, the Go driver for MySQL ignores this convention for some reason known only to its developers. Before trying the connection, the Go driver resolves the hostname in your connection string, so it silently translates "localhost" to 127.0.0.1. For MySQL, this means it’s literally connecting to a different user than the one you intended.
To use the UNIX domain socket in the Go mysql driver, read the documentation:
The Go mysql driver has established its own conventions for connection strings.