admissionServer/databaseConnection.go

97 lines
2.3 KiB
Go
Raw Normal View History

package main
import (
"context"
"database/sql"
"fmt"
"log"
"strconv"
_ "github.com/denisenkom/go-mssqldb"
)
var connectionString = "server=192.168.43.241;Port=62262;database=DB_s439397;trusted_connection=yes;encrypt=disable"
//var connectionString = "server=MARCEL\\SQLEXPRESS;user id=;password="
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
func readDatabase(tableName string) (iDatabaseModels, error) {
ctx := context.Background()
checkIsDatabaseAlive()
tsql := "SELECT * FROM " + tableName
rows, _ := db.QueryContext(ctx, tsql)
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()
tsql := "UPDATE " + tableName + " SET " + fieldToUpdate + " = '" + valueToInsert +
"' WHERE " + primaryKeyName + " = '" + primaryKey + "'"
result, _ := db.ExecContext(ctx, tsql)
toReturn, _ := result.RowsAffected()
return (strconv.FormatInt(toReturn, 10))
}
func insertRecord(command string) string {
ctx := context.Background()
checkIsDatabaseAlive()
/*tsql := "INSERT " + tableName + " VALUES '" + primaryKey + "'"
for i := 0; i<numberOfValues; i++ {
tsql = tsql + ", '" + valuesList[i] + "'"
}*/
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
}