go - 使用 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)
}
解决方案
想通了。导入了错误的 pkg。
替代
"gorm.io/driver/mysql"
代替
"github.com/go-sql-driver/mysql"
修复它。
推荐阅读
- javascript - MIME 类型('text/html')的 Express 服务器问题
- for-loop - 仅在文件夹层次结构的子集中使用 FOR /R 进行递归搜索
- javascript - 在使用 setTimeout 函数时在 Vue 中使用 v-show 或 v-if 切换可见性
- c# - 实体框架核心:DbContext 不链接实体
- azure-functions - Azure 函数计划和运行
- asp.net - 在 SQL 命令中添加 '%
- samba - 发送文件到 smb 服务器
- java - Sentry 不会从 Spark 作业中捕获异常
- laravel - Laravel 查询返回错误数据
- migration - Wildfly - 将 Wildfly 从 8.2.1 迁移到 21.0.0