首页 > 解决方案 > 使用 Gorm 未定义:mysql.Open

问题描述

查看了 gorm 的文档,我认为我正确地遵循了模式。我已经运行 go build 和 go mod tidy。

但仍然存在相同的错误。

包主

import (
    "encoding/json"
    "github.com/go-sql-driver/mysql"
    "gorm.io/gorm"
    "net/http"
)

var DB *gorm.DB
var err error

const DNS = "root:654321cg@tcp(127.0.0.1:3306)/resourcesdb?charset=utf8&parseTime=True&loc=Local"

...

func InitialMigration()  {
    DB, err = gorm.Open(mysql.Open(DNS), &gorm.Config{})
    if err != nil {
        println(err.Error())
        panic("Cannot connect to DB")
    }
    DB.AutoMigrate(&Client{})
}



func createClient(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var client Client
    json.NewDecoder(r.Body).Decode(&client)
    DB.Create(&client)
    json.NewEncoder(w).Encode(client)
}

标签: gomysql-connector

解决方案


想通了。导入了错误的 pkg。

替代

"gorm.io/driver/mysql"

代替

"github.com/go-sql-driver/mysql"

修复它。


推荐阅读