2022-07-05 12:38:39 +02:00
|
|
|
package advsql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Database struct {
|
|
|
|
db *sql.DB
|
|
|
|
closefuncs []func() error
|
|
|
|
}
|
|
|
|
|
2022-07-08 22:09:53 +02:00
|
|
|
func NewDatabase(conn *sql.DB) *Database {
|
|
|
|
return &Database{
|
|
|
|
db: conn,
|
|
|
|
closefuncs: make([]func() error, 0),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-11 13:05:16 +02:00
|
|
|
func NewMysqlDatabase(host string, port uint16, user, pass, db string) *Database {
|
2022-07-05 12:38:39 +02:00
|
|
|
conn, err := sql.Open("mysql", connString(host, port, user, pass, db))
|
|
|
|
if err != nil {
|
2022-07-11 13:05:16 +02:00
|
|
|
panic(err)
|
2022-07-05 12:38:39 +02:00
|
|
|
}
|
2022-07-11 13:05:16 +02:00
|
|
|
return NewDatabase(conn)
|
2022-07-05 12:38:39 +02:00
|
|
|
}
|
|
|
|
|
2022-07-11 13:05:16 +02:00
|
|
|
func (db *Database) prepare(query string) *sql.Stmt {
|
2022-07-05 12:38:39 +02:00
|
|
|
s, err := db.db.Prepare(query)
|
|
|
|
if err != nil {
|
2022-07-11 13:05:16 +02:00
|
|
|
panic(err)
|
2022-07-05 12:38:39 +02:00
|
|
|
}
|
|
|
|
db.closefuncs = append(db.closefuncs, s.Close)
|
2022-07-11 13:05:16 +02:00
|
|
|
return s
|
2022-07-05 12:38:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (db *Database) Close() error {
|
|
|
|
for _, close := range db.closefuncs {
|
|
|
|
close()
|
|
|
|
}
|
|
|
|
return db.db.Close()
|
|
|
|
}
|