Sum in GoLang and MySQL

This project will demonstrate how to use Sum in GoLang and MySQL

  • LearnGoLangAndMySQL
    • src
      • config
        • config.go
      • entities
        • product_entity.go
      • models
        • product_model.go
      • main.go
package models

import (
    "database/sql"
    "entities"
)

type ProductModel struct {
    Db *sql.DB
}

func (productModel ProductModel) SumQuantities() (int64, error) {
    rows, err := productModel.Db.Query("select sum(quantity) as sum_quantities from product")
    if err != nil {
        return 0, err
    } else {
        var sum_quantities int64
        for rows.Next() {
            rows.Scan(&sum_quantities)
        }
        return sum_quantities, nil
    }
}

func (productModel ProductModel) Total() (float64, error) {
    rows, err := productModel.Db.Query("select sum(price * quantity) as total from product")
    if err != nil {
        return 0, err
    } else {
        var total float64
        for rows.Next() {
            rows.Scan(&total)
        }
        return total, nil
    }
}
package main

import (
    "config"
    "fmt"
    "models"
)

func main() {
    db, err := config.GetMySQLDB()
    if err != nil {
        fmt.Println(err)
    } else {
        productModel := models.ProductModel{
            Db: db,
        }

        sumQuantities, err2 := productModel.SumQuantities()
        if err2 != nil {
            fmt.Println(err2)
        } else {
            fmt.Println("Sum Quantities:", sumQuantities)
        }

        total, err3 := productModel.Total()
        if err3 != nil {
            fmt.Println(err3)
        } else {
            fmt.Println("Total:", total)
        }
    }
}
package entities

type Product struct {
    Id       int64
    Name     string
    Price    float32
    Quantity int
    Status   bool
}
package config

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

func GetMySQLDB() (db *sql.DB, err error) {
    dbDriver := "mysql"
    dbUser := "root"
    dbPass := "123456"
    dbName := "learngodb"
    db, err = sql.Open(dbDriver, dbUser + ":" + dbPass + "@/" + dbName)
    return
}

Screenshots