44 lines
790 B
Go
44 lines
790 B
Go
package advsql
|
|
|
|
import (
|
|
"database/sql"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
)
|
|
|
|
type Database struct {
|
|
db *sql.DB
|
|
closefuncs []func() error
|
|
}
|
|
|
|
func NewDatabase(conn *sql.DB) *Database {
|
|
return &Database{
|
|
db: conn,
|
|
closefuncs: make([]func() error, 0),
|
|
}
|
|
}
|
|
|
|
func NewMysqlDatabase(host string, port uint16, user, pass, db string) *Database {
|
|
conn, err := sql.Open("mysql", connString(host, port, user, pass, db))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return NewDatabase(conn)
|
|
}
|
|
|
|
func (db *Database) prepare(query string) *sql.Stmt {
|
|
s, err := db.db.Prepare(query)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
db.closefuncs = append(db.closefuncs, s.Close)
|
|
return s
|
|
}
|
|
|
|
func (db *Database) Close() error {
|
|
for _, close := range db.closefuncs {
|
|
close()
|
|
}
|
|
return db.db.Close()
|
|
}
|