databaseutils.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package databaseutils
  2. import (
  3. "database/sql"
  4. _ "github.com/go-sql-driver/mysql"
  5. "fmt"
  6. )
  7. type DBUtils struct {
  8. User string
  9. Password string
  10. Host string
  11. Database string
  12. Handle *sql.DB
  13. }
  14. // db := dbUtils{"root", "root", "127.0.0.1", "gotest"}
  15. func (dbUtil DBUtils) Connect() {
  16. var err error
  17. dbUtil.Handle, err = sql.Open("mysql", dbUtil.User + ":" + dbUtil.Password + "@tcp(" + dbUtil.Host + ")/" + dbUtil.Database)
  18. if err != nil {
  19. panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
  20. }
  21. // Open doesn't open a connection. Validate DSN data:
  22. err = dbUtil.Handle.Ping()
  23. if err != nil {
  24. panic(err.Error()) // proper error handling instead of panic in your app
  25. }
  26. fmt.Printf("%v", dbUtil)
  27. }
  28. func (dbUtil DBUtils) Close() {
  29. dbUtil.Handle.Close()
  30. }
  31. func (dbUtil DBUtils) GetString(what string, from string, where string, wherevalue string) string {
  32. var username string
  33. fmt.Printf("%v", dbUtil)
  34. stmtOut, err := dbUtil.Handle.Prepare("SELECT " + what + " FROM " + from + " WHERE " + where + " = " + wherevalue)
  35. if err != nil {
  36. panic(err.Error()) // proper error handling instead of panic in your app
  37. }
  38. err = stmtOut.QueryRow(1).Scan(&username)
  39. return username
  40. }