Referring to an open database connection inside a function - Golang

前端 未结 1 673
日久生厌
日久生厌 2021-01-12 21:00

My main function opens a database connection:

func main() {
    db, err := sql.Open(\"sqlite3\", \"./house.db\")
    checkErr(err)

    ...
}
相关标签:
1条回答
  • 2021-01-12 21:24

    Depending on how your application works, you can either

    1. keep the db global
    2. pass db as a parameter
    3. make addRoom a method

    What I typically do for API services is create a global db, like this:

    var db *sql.DB
    
    func main() {
        var err error
        db, err = sql.Open("sqlite3", "./house.db")
        checkErr(err)
        // create room Room{}
        err = addRoom(room)
        checkErr(err)
    }
    

    But you can also pass db as a parameter:

    func addRow(db *sql.DB, row Room) error
    

    Or you can create a struct which keeps the connection as an attribute and makes addRow a method:

    type dbConn struct {
        db *sql.DB
    }
    
    func (conn dbConn) addRow(row Room) error
    

    This book has some nice examples.

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