advsql/db.go

42 lines
834 B
Go
Raw Normal View History

2022-07-05 12:38:39 +02:00
package advsql
import (
"database/sql"
"git.tordarus.net/Tordarus/adverr"
_ "github.com/go-sql-driver/mysql"
)
type Database struct {
db *sql.DB
closefuncs []func() error
}
func NewDatabase(host string, port uint16, user, pass, db string) (*Database, error) {
conn, err := sql.Open("mysql", connString(host, port, user, pass, db))
if err != nil {
return nil, adverr.Wrap("could not connect to database", err)
}
return &Database{
db: conn,
closefuncs: make([]func() error, 0),
}, nil
}
func (db *Database) prepare(query string) (*sql.Stmt, error) {
s, err := db.db.Prepare(query)
if err != nil {
return nil, err
}
db.closefuncs = append(db.closefuncs, s.Close)
return s, nil
}
func (db *Database) Close() error {
for _, close := range db.closefuncs {
close()
}
return db.db.Close()
}