-2

TLDR; Error attempting to access DB with Golang

I am trying to connect to my localhost db using the example here. The go code for connecting to the DB can be found below.

func main() {
    // Capture connection properties.
    cfg := mysql.Config{
        User:   os.Getenv("DBUSER"),
        Passwd: os.Getenv("DBPASS"),
        Net:    "tcp",
        Addr:   "127.0.0.1:3306",
        DBName: "someDB",
    }

    // Get a database handle.
    var err error
    db, err = sql.Open("mysql", cfg.FormatDSN())
    if err != nil {
        log.Fatal(err)
    }

    pingErr := db.Ping()
    if pingErr != nil {
        log.Fatal(pingErr)
    }
    fmt.Println("Connected!")

}

I see the this output

✗ go run main.go
2023/02/17 00:10:35 Error 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I have tried:

  • confirmed that DBUSER and DBPASS are set with the expected value
  • I am able to mysql -u root -p and connect to DB without any issues.
kostix
  • 51,517
  • 14
  • 93
  • 176
  • There are a large number of previous post about PHP having this issue. I checked most of the previous post, and I did not see a Golang post. – YouWontBreakMySoul Feb 17 '23 at 14:39
  • https://stackoverflow.com/questions/21944936/error-1045-28000-access-denied-for-user-rootlocalhost-using-password-y According to this post this happens with blank passwords or password=password. If that is the case and you are the admin you might try a different one. – h0ch5tr4355 Feb 17 '23 at 14:50
  • Thanks @h0ch5tr4355, but this is not my case. I am able to execute `mysql -u root -p` with a password not equal to "password". This does not appear to be my case. – YouWontBreakMySoul Feb 17 '23 at 15:01
  • «If `mysql -u user_name` works but `mysql -u user_name some_db` does not, you have not granted access to the given user for the database named `some_db`.» from [the troubleshooting guide](https://dev.mysql.com/doc/refman/5.7/en/problems-connecting.html) is likely the reason because the Go MySQL driver supposedly tries to connect to the DB specfied in the `mysql.Config` passed to it. I'd start with printing the result of `cfg.FormatDSN()` to have a better idea of what's happening. All in all, this is not a question about programming in Go. – kostix Feb 17 '23 at 15:13
  • Thanks @kostix. `mysql -u user_name some_db` will not work because a password is expected. Printing `cfg.FormatDSN()` outputs `tcp(127.0.0.1:3306)/someDB?allowNativePasswords=false&checkConnLiveness=false&maxAllowedPacket=0` I am confused how this is not a go question, when I am able to connect to DB in my terminal? – YouWontBreakMySoul Feb 17 '23 at 16:47

1 Answers1

0

The solution to my problem was solved by updating my password. My password started with @. After I updated my password.

mysql -u root -h localhost -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'some-new-password';
mysql> FLUSH PRIVILEGES;

Now when I run my code I see Connected!