MySQL显示“错误1045:用户“root”@“localhost”的访问被拒绝(使用密码:是)",当我尝试使用Golang gorm包访问它时

bnl4lu3b  于 2022-11-21  发布在  Mysql
关注(0)|答案(1)|浏览(157)

这是我用的app.go文件

package config

import (
    "fmt"
    "log"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

var db *gorm.DB

func Connect() {
    dsn := "<root>:<password>@/simplerest?charset=utf8&parseTime=True&loc=Local"
    d, err := gorm.Open("mysql", dsn)
    if err != nil {
        panic(err)
    } else {
        log.Fatal("Connection established")
    }

    fmt.Printf("Type : %T", d)
    db = d
}

func GetDB() *gorm.DB {
    return db
}

当我试图运行我的app.go文件时,我总是收到错误消息。

panic: Error 1045: Access denied for user 'root'@'localhost' (using password: YES)

goroutine 1 [running]:
github.com/bedLad/go-bookstore/pkg/config.Connect()
        /home/root/development/go-code/go-bookstore/pkg/config/app.go:17 +0x12a
github.com/bedLad/go-bookstore/pkg/models.init.0()
        /home/root/development/go-code/go-bookstore/pkg/models/book.go:22 +0x19
exit status 2

我可以使用命令mysql -u root -p通过终端访问mySQL,因此密码根本不是问题

vngu2lb8

vngu2lb81#

按如下方式格式化您的DSN:

dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, password, hostname, port, dbname) + "?charset=utf8mb4&parseTime=True&loc=Local"
  db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
  if err != nil {
      fmt.Println(err)
      return
  } else {
    fmt.Println("Connected")
  }

相关问题