I am using the following code to wrap execution of aquery on a postgres database in a API I am building just to learn Go.
func QueryDB(qstring string) (*sql.Rows) {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=disable", host, port, user, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
//Ping method opens the connection
err = db.Ping()
if err != nil {
panic(err)
}
//rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)
log.Printf("executing SQL %s\n",qstring)
rows, err := db.Query(qstring)
if err != nil {
log.Fatal(err)
}
return rows
}
my question is as per the documentation the db.Query() method accepts a query strgin and ...interface{} arguments otherwise. tried adding a second argument params ...interface{} to my function arguments and passing params as the second argument to the DB.Query method, and this doesn't work. it only seems to work if I specifically pull the arguments out of the interface slice. Any suggestions?
sql.Openis meant to open and maintain a connection pool to the database. You will want toOpenit once, and reuse the handle it returns. The library itself will maintain the base connection and spin up/down any necessary additional connections.Mainfunction if something like a one-offsql.Openfails because that is something you would want to terminate your own program. It's something your application simply cannot function without.