Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

gorm的问题,为了全局使用db,我定义了全局变量,如果分成多个文件,db对象如何获取?

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "log"
)

var db *gorm.DB
var err error

func main() {
    r := gin.Default()
    dsn := "root:Nexon8888@tcp(127.0.0.1:3306)/iapplus?charset=utf8mb4&parseTime=True&loc=Local"
    db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err!=nil {
        log.Fatal("数据库连接错误")
    }
    r.GET("/ping/:name", ping)
    r.Run("127.0.0.1:8081") // listen and serve on 0.0.0.0:8080
}

func ping(c *gin.Context) {
    //c.JSON(200, gin.H{
    //    "message": "pong",
    //})
    var user UserModel
    db.First(&user)
    fmt.Println(user.ID)
    fmt.Println(user.Mobile)
    c.String(200, "Hello World"+c.Param("name"))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

定义一个model 包,或者 const 的包

image.png

然后在 main 里面导入这个 model

初始化链接上数据库后,就可以
model.DB = db

然后其他包只需要引入 model , 再 model.DB 就可以愉快的使用了

image.png

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...