sprechstunden-go/sqldb/sqldb.go

51 lines
1 KiB
Go
Raw Normal View History

2022-08-29 20:58:19 +00:00
package sqldb
import (
"database/sql"
"fmt"
"log"
"sprechstundentool/config"
2022-08-29 20:58:19 +00:00
_ "github.com/go-sql-driver/mysql"
2022-08-29 20:58:19 +00:00
_ "github.com/mattn/go-sqlite3"
)
func Connect(config config.Config) *sql.DB {
switch config.SQL.Type {
case "SQLite":
return connectSQLite(config.SQL.SQLiteFile)
case "Mysql":
return connectMysql(config.SQL.MysqlUser,
config.SQL.MysqlPassword,
config.SQL.MysqlHost,
config.SQL.MysqlPort,
config.SQL.MysqlDatabase)
default:
log.Fatal("Type of database not recognised.")
}
return nil
}
func connectSQLite(file string) *sql.DB {
db, err := sql.Open("sqlite3", file)
2022-08-29 20:58:19 +00:00
if err != nil {
log.Fatal(err)
2022-08-29 20:58:19 +00:00
}
return db
}
func connectMysql(user string, password string, address string, port int, database string) *sql.DB {
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, password, address, port, database))
if err != nil {
log.Fatalf("Error connecting to database: %s", err)
}
err = db.Ping()
// handle error
if err != nil {
log.Fatalf("Error pinging database: %s", err)
}
return db
}