使用 Gorm 变得不确定:mysql.Open
Using Gorm getting undefined: mysql.Open
查看了 gorm 的文档,我认为我遵循的模式是正确的。我有 运行 去构建并去 mod 整理。
但仍然存在同样的错误。
主要包
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"
修复它。
将 "github.com/go-sql-driver/mysql"
替换为 "gorm.io/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)
}
查看了 gorm 的文档,我认为我遵循的模式是正确的。我有 运行 去构建并去 mod 整理。
但仍然存在同样的错误。
主要包
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"
修复它。
将 "github.com/go-sql-driver/mysql"
替换为 "gorm.io/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)
}