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

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

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来