2015-03-02 99 views
0

我想要完成的是在多個函數之間共享一個db.sqlx指針,除了指示傳遞指針的帖子,這很好,但是如何在一個接口?我找不到任何說明在任何地方使用此功能的東西。基本上我所擁有的是一個Datastore類型的接口。我也有實現數據存儲類型的mysql & pgsql。該接口本身工作正常,但問題是我想創建一個單一的連接函數* sqlx.DB在實現的接口內的所有功能共享。我認爲問題在於我對如何共享界面功能之間的指針甚至是「共享它」的「何處」感到困惑。主界面看上去象下面這樣:在golang中共享接口之間的連接指針

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是關閉錯誤。那麼,如何正確地共享函數之間的數據庫連接,還是我真的必須在每個函數中運行打開的連接?

回答

2

不要致電推遲db.Close()在你的initDB函數。在執行該函數後,db也會關閉!所以當你打電話給你的方法時,你會得到封閉的錯誤。
也許你需要重新您DESGIN接口,例如:

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 
} 
+0

感謝上的幫助。 – 2015-03-02 17:36:12

+0

在Close中,應該是my.db.Close()嗎? – 2015-03-02 18:49:56

+0

@AustinMullins啊是的,我會編輯答案! – nvcnvn 2015-03-03 15:27:35