【问题标题】:Sharing of conn pointer between interfaces in golanggolang接口间conn指针共享
【发布时间】:2015-03-02 17:09:25
【问题描述】:

我想要完成的是在多个函数之间共享 db.sqlx 的指针,除了帖子说传递指针,这很好,但是如何在接口中做到这一点?我找不到任何可以说明在任何地方使用它的东西。基本上我拥有的是数据存储类型的接口。我也有实现 Datastore 类型的 mysql & pgsql。该接口本身工作正常,但问题是我正在尝试为 *sqlx.DB 创建一个连接函数,以便在实现的接口中的所有函数之间共享。我认为问题是我对如何在接口的函数之间共享指针甚至“在哪里”共享它感到困惑。主界面如下图:

var (
    storage Datastore
    db * sqlx.DB
)

type Datastore interface {
    Insert(db *sqlx.DB, table string, item DataItem) bool
    CheckEmpty(db *sqlx.DB, table string) bool
    FetchAll(db *sqlx.DB, table string) []DataItem
    DBInit(db *sqlx.DB)
    initDB()
}

在我实现的接口(简化的 mysql 示例)中,我有如下所示的 initDB 函数:

type MySQLDB struct {
    config *config.Configuration
}


func (my *MySQLDB) initDB() {
    log.Println("Getting DB Connection")
    tempdb, err := sqlx.Connect("mysql", my.config.Database.Dsn+"&parseTime=True")
    if err != nil {
        log.Println(err.Error())
    }
    db = tempdb
    defer db.Close()
}

func (my *MySQLDB) FetchAll(db *sqlx.DB, table string) []DataItem {
    dTable := []DataItem{}
    query := "SELECT foo, bar FROM " + table + " ORDER BY last_update ASC"
    err := db.Select(&dTable, query)
    if err != nil{
        panic(err)
    }
    return dTable
}

此时我知道连接最初是打开的,但是下次调用函数时,我得到 db is closed 错误。那么如何在函数之间正确共享数据库连接,或者我真的必须在每个函数中运行一个打开的连接?

【问题讨论】:

    标签: go


    【解决方案1】:

    不要在 initDB 函数中调用 defer db.Close()。执行该函数后,db 也将关闭!因此,当您调用您的方法时,您会收到关闭的错误。
    也许你需要重新设计你的界面,例如:

    type Datastore interface {
        Insert(table string, item DataItem) bool
        CheckEmpty(table string) bool
        FetchAll(table string) []DataItem
        Close() error // call this method when you want to close the connection
        initDB()
    }
    

    您的 MySQLDB 实现现在如下所示:

    type MySQLDB struct {
        config *config.Configuration
        db *sqlx.DB
    }
    
    
    func (my *MySQLDB) initDB() {
        log.Println("Getting DB Connection")
        tempdb, err := sqlx.Connect("mysql", my.config.Database.Dsn+"&parseTime=True")
        if err != nil {
            log.Println(err.Error())
        }
        my.db = tempdb
    }
    
    func (my *MySQLDB) Close() error {
        return my.db.Close()
    }
    
    func (my *MySQLDB) FetchAll(table string) []DataItem {
        dTable := []DataItem{}
        query := "SELECT foo, bar FROM " + table + " ORDER BY last_update ASC"
        err := my.db.Select(&dTable, query)
        if err != nil{
            panic(err)
        }
        return dTable
    }
    

    【讨论】:

    • 感谢您的帮助。
    • Close,应该是my.db.Close()吗?
    猜你喜欢
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多