45 lines
783 B
Go
45 lines
783 B
Go
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
_ "github.com/lib/pq"
|
|
)
|
|
|
|
type Database struct {
|
|
Host string
|
|
Port int
|
|
connection *sql.DB
|
|
}
|
|
|
|
func NewDatabase(host string, port int) Database {
|
|
return Database{
|
|
Host: host,
|
|
Port: port,
|
|
}
|
|
}
|
|
|
|
func (d *Database) Connect(user string, password string, dbname string) error {
|
|
connectionString := fmt.Sprintf("postgresql://%s:%s@%s:%d?sslmode=disable", user, password, d.Host, d.Port)
|
|
|
|
conn, err := sql.Open(dbname, connectionString)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
d.connection = conn
|
|
|
|
return nil
|
|
}
|
|
|
|
func (d Database) Execute(sql string) error {
|
|
if d.connection == nil {
|
|
return errors.New("Cannot execute SQL without being connected to a database.")
|
|
}
|
|
|
|
_, err := d.connection.Exec(sql)
|
|
|
|
return err
|
|
}
|