How do I connect to a MySQL instance without using the password?

Viewed 2208

I trying to connect db I have set no password for the db I am leaving blank in the password field. But it's not connecting and showing error connector.go:95: could not use requested auth plugin 'mysql_native_password': this user requires mysql native password authentication.. Also I am using phpmyadmin as db so how to connect here is my code

package main

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

var db *sql.DB

func main() {
    // Capture connection properties.
    cfg := mysql.Config{
        User:   "root",
        Passwd: "",
        Net:    "tcp",
        Addr:   "127.0.0.1:3306",
        DBName: "recordings",
    }
    // 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!")
}

2 Answers

That looks a lot like the code from the Tutorial: Accessing a relational database which unfortunately does not work. You need to specify AllowNativePasswords: true for it to work. That value is true by default, but the defaults are only applied if you use NewConfig() and not create the Config struct yourself. But this will work as well:

    cfg := mysql.Config{
        User:                 "root",
        Passwd:               "",
        Net:                  "tcp",
        Addr:                 "127.0.0.1:3306",
        DBName:               "recordings",
        AllowNativePasswords: true,
    }

Try to change authentication plugin of root user to mysql_native_password in your database. More information about here

UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';
Related