skip to Main Content

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


  1. Maybe there is an error with the sqlx package. Try using the sql package like this:

    db, err = sql.Open("mysql", "root:xxx@tcp(localhost:3306)/mydb")
    
    Login or Signup to reply.
  2. 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:

    For TCP and UDP networks, addresses have the form host[:port]. If port is omitted, the default port will be used. If host is a literal IPv6 address, it must be enclosed in square brackets. The functions net.JoinHostPort and net.SplitHostPort manipulate addresses in this form.

    For Unix domain sockets the address is the absolute path to the MySQL-Server-socket, e.g. /var/run/mysqld/mysqld.sock or /tmp/mysql.sock.

    The Go mysql driver has established its own conventions for connection strings.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search