dongxia5394 2019-01-14 08:52
浏览 155
已采纳

如何将连接参数db传递给main.go?

I have trouble with my current works. I build an apps using beego framework, Im new in golang.

First, I build other package called utils, and from that package I write some codes to access to my databases

func InitFirebird() {
    var (
        dbDriver   = beego.AppConfig.String("DB_CONNECTION")
        dbUsername = beego.AppConfig.String("DB_USERNAME")
        dbPassword = beego.AppConfig.String("DB_PASSWORD")
        dbServer   = beego.AppConfig.String("DB_HOST")
        // dbPort     = beego.AppConfig.String("DB_PORT")
        dbFileName = beego.AppConfig.String("DB_DATABASE")
    )
    conn, _ := sql.Open(dbDriver, dbUsername+":"+dbPassword+"@"+dbServer+"/"+dbFileName)
    defer conn.Close()
}

After that, I go to my main.go and setting up my init function and main function like this:

func init() {
    utils.InitFirebird()
}

func main() {
    if beego.BConfig.RunMode == "dev" {
        beego.BConfig.WebConfig.DirectoryIndex = true
        beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
        }

    var n int

    conn.QueryRow("SELECT Count(*) FROM rdb$relations").Scan(&n)
    fmt.Println("Relations count=", n)

    beego.Run()
}

When I startover my apps, its error and provide me this message :

\main.go:23:2: undefined: conn

How can I resolve this?

Anyhelp will appreciate

  • 写回答

1条回答 默认 最新

  • douliang1900 2019-01-14 09:03
    关注

    First, if you want to access something from another package, it has to be exported. In Go, if you want to export something you name it with first letter as uppercase (in your case, it should be Conn instead of conn).

    Second, when you use defer it will get executed when the function returns. In your case, it returns immediately, so the connection is closed immediately.

    Solution:

    var Conn *sql.DB
    func InitFirebird() {
        var (
            dbDriver   = beego.AppConfig.String("DB_CONNECTION")
            dbUsername = beego.AppConfig.String("DB_USERNAME")
            dbPassword = beego.AppConfig.String("DB_PASSWORD")
            dbServer   = beego.AppConfig.String("DB_HOST")
            // dbPort     = beego.AppConfig.String("DB_PORT")
            dbFileName = beego.AppConfig.String("DB_DATABASE")
        )
        Conn, _ = sql.Open(dbDriver, dbUsername+":"+dbPassword+"@"+dbServer+"/"+dbFileName)
    }
    

    Now in your main package:

    func init() {
        utils.InitFirebird()
    }
    
    func main() {
        if beego.BConfig.RunMode == "dev" {
            beego.BConfig.WebConfig.DirectoryIndex = true
            beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
            }
    
        var n int
        defer utils.Conn.Close() // <-- Close here
    
        utils.Conn.QueryRow("SELECT Count(*) FROM rdb$relations").Scan(&n)
        fmt.Println("Relations count=", n)
    
        beego.Run()
    }
    

    Here Close() won't get executed immediately because beego.Run() will block.

    PS: Passing DB connection using global variable is not recommended. If you want to learn more check this out: https://www.alexedwards.net/blog/organising-database-access

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错
  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数