duanjiongzhen2523 2015-03-02 17:09
浏览 120
已采纳

在golang中的接口之间共享conn指针

What I'm trying to accomplish is sharing a pointer of db.sqlx between multiple functions, except for posts saying pass along the pointer, which is fine but how to do that in an interface? I cannot find anything that illustrates the use of this anywhere. Basically what I have is an interface of type Datastore. I also have mysql & pgsql that implements the Datastore type. The interface by itself works fine however the issue is I'm trying to create a single connect function for *sqlx.DB to be shared across all functions within the implemented interface. I think the issue is I've confused myself on how to share the pointer between functions of the interface or even "where" to share it. The main interface looks like below:

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()
}

Within my implemented interface (simplified mysql example) I have the initDB function which looks like this:

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
}

At this point I know the connection is initially opened but the next time a function is called I get db is closed error. So how do I properly share the db connection between functions, or do I really have to run a connection open in every function?

  • 写回答

1条回答 默认 最新

  • dsfgdsjfd78773 2015-03-02 17:24
    关注

    Don't call defer db.Close() in your initDB function. After that function executed, db will close too! So when you call your method you get the closed error.
    Maybe you need to re-desgin your interface, for example:

    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()
    }
    

    Your MySQLDB implement now look like:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器