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 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输