douju7245 2015-04-05 22:29
浏览 124
已采纳

将数据库连接存储在全局变量中

I'm using the MySQL driver for Golang provided here

https://github.com/go-sql-driver/mysql

One of the things I'm trying to do is store the database variable in a global connection. According to the documentation, sql.Open() is supposed to return a pointer to a DB struct, so I tried storing it as

var db *DB

However, that resulted in the error

undefined: DB

The next thing I tried was to look at the source code for the MySQL driver, and I found a snippet of code here https://github.com/go-sql-driver/mysql/blob/master/driver.go

func (d MySQLDriver) Open(dsn string) (driver.Conn, error) {

So, I tried to save the variable as driver.Conn - however, I was unable to (incorrect imports). I wasn't able to import driver either.

The last thing I tried was to use reflect to bring the name of the variable to light

package main

    import (
        "fmt"
        "reflect"
)

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

func main() {
        db, _ := sql.Open("mysql", "root:password@/Tracker")
        yt := reflect.TypeOf(db).Kind()
        fmt.Printf("%T: %s
", yt, yt)
}

Unfortunately, that didn't work either - it shows up as pointer, and not the type of variable it's actually pointing to.

I'm at a loss as to how to figure it out now. Thanks in advance for your help!

  • 写回答

1条回答 默认 最新

  • dtu15253 2015-04-05 22:41
    关注

    You need to qualify the name of the type with the package name:

    import(
        "database/sql"
        "github.com/go-sql-driver/mysql"
    )
    
    var db *sql.DB // Note the sql package provides the namespace
    
    func main() {
        var err error
        // Make sure not to shadow your global - just assign with = - don't initialise a new variable and assign with :=
        db, err = sql.Open(...)
        if err != nil {
            // Handle the error!
        }
    
     }
    

    Whether you want to have a global (easy to get started) or pass it around explicitly is up to you, but I'd suggest just keeping it simple for now. If this is going into a web application, you can safely share the *sql.DB connection pool across handlers/requests.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么