admissionServer/databaseConnection.go

111 lines
2.5 KiB
Go

package main
import (
"context"
"database/sql"
"fmt"
"log"
"strconv"
_ "github.com/denisenkom/go-mssqldb"
)
var connectionString = "server=192.168.1.2;Port=1433;database=DB_s439397;trusted_connection=yes;encrypt=disable"
var db *sql.DB
var err error
func testConnection() {
db, err = sql.Open("sqlserver", connectionString)
if err != nil {
log.Fatal("Error creating connection pool: ", err.Error())
}
//ctx := context.Background()
err = db.Ping()
//err = db.PingContext(ctx)
if err != nil {
log.Fatal(err.Error())
}
fmt.Printf("Connected!\n")
}
type iHasValue interface{}
type values []iHasValue
// ODCZYT Z BAZY DANYCH BEZ SORTOWANIA
func readDatabase(command string, tableName string) (iDatabaseModels, error) {
ctx := context.Background()
checkIsDatabaseAlive()
rows, _ := db.QueryContext(ctx, command)
defer rows.Close()
var models iDatabaseModels
models = nil
switch tableName {
case "Lekarze":
var x doctors
models = x.readModels(rows)
case "Pacjenci":
var x patients
models = x.readModels(rows)
case "Operacje":
var x operations
models = x.readModels(rows)
case "Diagnozy":
var x diagnoses
models = x.readModels(rows)
case "Przyjecia":
var x admissions
models = x.readModels(rows)
case "Sale":
var x rooms
models = x.readModels(rows)
}
return models, nil
}
func updateRecord(tableName string, primaryKey string,
primaryKeyName string, fieldToUpdate string, valueToInsert string) string {
ctx := context.Background()
checkIsDatabaseAlive()
if valueToInsert == "null" {
valueToInsert = "NULL"
} else {
valueToInsert = "'" + valueToInsert + "'"
}
tsql := "UPDATE " + tableName + " SET " + fieldToUpdate + " = " + valueToInsert +
" WHERE " + primaryKeyName + " = '" + primaryKey + "'"
result, er := db.ExecContext(ctx, tsql)
if er == nil {
toReturn, _ := result.RowsAffected()
return (strconv.FormatInt(toReturn, 10))
}
return "ERROR"
}
func insertRecord(command string) string {
ctx := context.Background()
checkIsDatabaseAlive()
result, er := db.ExecContext(ctx, command)
if er == nil {
toReturn, _ := result.RowsAffected()
return (strconv.FormatInt(toReturn, 10))
}
return "ERROR"
}
func deleteRecord(command string) string {
ctx := context.Background()
checkIsDatabaseAlive()
result, _ := db.ExecContext(ctx, command)
toReturn, _ := result.RowsAffected()
return (strconv.FormatInt(toReturn, 10))
}
func checkIsDatabaseAlive() error {
err = db.Ping()
if err != nil {
log.Fatal(err.Error())
}
return nil
}