cpolis/cmd/data/db.go

35 lines
657 B
Go
Raw Normal View History

package data
import (
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
)
type DB struct {
*sql.DB
}
func OpenDB(dbName string) (*DB, error) {
var err error
db := DB{DB: &sql.DB{}}
cfg := mysql.NewConfig()
cfg.DBName = dbName
cfg.User, cfg.Passwd, err = getCredentials()
if err != nil {
return nil, fmt.Errorf("error: user credentials for DB could not be read: %v", err)
}
db.DB, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return nil, fmt.Errorf("error: DB could not be opened: %v", err)
}
if err = db.Ping(); err != nil {
return nil, fmt.Errorf("error: DB could not be reached: %v", err)
}
return &db, nil
}