My main function opens a database connection:
func main() {
db, err := sql.Open(\"sqlite3\", \"./house.db\")
checkErr(err)
...
}
Depending on how your application works, you can either
db
globaldb
as a parameteraddRoom
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.