databaseutils.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. }
  27. func (dbUtil DBUtils) Close() {
  28. dbUtil.Handle.Close()
  29. }
  30. func (dbUtil DBUtils) GetString(what string, from string, where string, wherevalue string) string {
  31. var username string
  32. rows, err := dbUtil.Handle.Query("SELECT " + what + " FROM " + from + " WHERE " + where + " = " + wherevalue)
  33. if err != nil {
  34. fmt.Println(err)
  35. }
  36. defer rows.Close()
  37. for rows.Next() {
  38. err := rows.Scan(&username)
  39. if err != nil {
  40. fmt.Println(err)
  41. }
  42. fmt.Println(username)
  43. }
  44. err = rows.Err()
  45. if err != nil {
  46. fmt.Println(err)
  47. }
  48. return username
  49. /*
  50. stmtOut, err := dbUtil.Handle.Prepare("SELECT " + what + " FROM " + from + " WHERE " + where + " = " + wherevalue)
  51. if err != nil {
  52. panic(err.Error()) // proper error handling instead of panic in your app
  53. }
  54. fmt.Printf("%v", stmtOut)
  55. err = stmtOut.QueryRow(0).Scan(&username)
  56. fmt.Printf("%v", username)
  57. return username*/
  58. }