【问题标题】:Using Gorm getting undefined: mysql.Open使用 Gorm 未定义:mysql.Open
【发布时间】:2021-08-28 11:39:12
【问题描述】:

查看了 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)
}

【问题讨论】:

    标签: go mysql-connector


    【解决方案1】:

    "gorm.io/driver/mysql"替换"github.com/go-sql-driver/mysql"

    import (
        "encoding/json"
        "gorm.io/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 {
            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)
    }
    

    【讨论】:

    • 这与 OP 3 小时前的回答有何不同?
    【解决方案2】:

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

    替换

    "gorm.io/driver/mysql"
    

    而不是

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

    修复它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多