mysql.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package database
  2. import (
  3. "database/sql"
  4. "fmt"
  5. _ "github.com/go-sql-driver/mysql" // This package allow me to use exec command
  6. "rate-it-api/utils"
  7. )
  8. //"github.com/go-yaml/yaml"
  9. // MysqlExec Allow to execute a new query on mysql database
  10. func mysqlGetConnection() (*sql.DB, error) {
  11. config := utils.GetConfig()
  12. credentials := config.Mysql
  13. con, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", credentials.User, credentials.Password, credentials.Hostname, credentials.Port, credentials.Database))
  14. if err != nil {
  15. return con, err
  16. }
  17. return con, nil
  18. }
  19. // MysqlExecInsert Allow to execute a new insert query on mysql database
  20. func MysqlExecInsert(query string) (sql.Result, error) {
  21. con, err := mysqlGetConnection()
  22. var result sql.Result
  23. if err != nil {
  24. return result, err
  25. }
  26. result, err = con.Exec(query)
  27. if err != nil {
  28. return result, err
  29. }
  30. defer con.Close()
  31. return result, nil
  32. }
  33. // MysqlExecSelect Allow to execute a new insert query on mysql database
  34. func MysqlExecSelect(query string) (*sql.Rows, error) {
  35. con, err := mysqlGetConnection()
  36. var result *sql.Rows
  37. if err != nil {
  38. return result, err
  39. }
  40. result, err = con.Query(query)
  41. if err != nil {
  42. return result, err
  43. }
  44. defer con.Close()
  45. return result, nil
  46. }