You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Gorm操作MySQL时提示undefined: mysql.Open错误求助

问题解决方案

错误根因

你导入了错误的MySQL依赖包:github.com/go-sql-driver/mysql是Go标准库database/sql的原生MySQL驱动,没有提供mysql.Open方法,GORM专用的MySQL驱动包为gorm.io/driver/mysql。

修复步骤

  • 第一步:替换import语句中的MySQL驱动导入路径,将github.com/go-sql-driver/mysql替换为gorm.io/driver/mysql
  • 第二步:执行go get gorm.io/driver/mysql拉取对应依赖
  • 第三步:重新执行go mod tidy和go build验证问题

修正后核心代码片段

import (
    "encoding/json"
    // 替换为GORM官方MySQL驱动
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "net/http"
)

var DB *gorm.DB
var err error

// 注:原代码中DNS为DSN(数据源名称)的拼写笔误,不影响运行但建议按规范修正
const DSN = "root:654321cg@tcp(127.0.0.1:3306)/resourcesdb?charset=utf8&parseTime=True&loc=Local"

func InitialMigration()  {
    DB, err = gorm.Open(mysql.Open(DSN), &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)
}

内容的提问来源于stack exchange,提问作者user2799827

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:24:04