Does db.Close() need to be called?

前端 未结 1 1075
旧巷少年郎
旧巷少年郎 2020-12-18 07:10

So far the hardest part of Go has been understanding how to organize code. It seems incredibly simple on it\'s face but every time I\'ve tried to do anything I run into cir

1条回答
  •  囚心锁ツ
    2020-12-18 07:59

    It's not necessary to close the DB.

    The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

    From: https://golang.org/pkg/database/sql/#Open

    When your program exits then any open connection is closed, it does not stay open somewhere in the ether awaiting your program to start again, so do not worry about the connections "growing" when you CTRL-C your app.


    If, however, you still want to close it, then you can just export a CloseDB function the same way you do with GetDB.

    App.go

    // ...
    
    func CloseDB() error {
        return db.Close()
    }
    

    main.go

    // ...
    
    func main() {
        // ...
    
        app.Setup()
        defer app.CloseDB()
    
        // ...
    
    }
    

    0 讨论(0)
提交回复
热议问题