Update in GoLang and MySQL

This project will demonstrate how to use Update 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) Update(product *entities.Product) (int64, error) {
    result, err := productModel.Db.Exec("update product set name = ?, price = ?, quantity = ?, status = ? where id = ?", product.Name, product.Price, product.Quantity, product.Status, product.Id)
    if err != nil {
        return 0, err
    } else {
        return result.RowsAffected()
    }
}
package main

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

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

        productModel := models.ProductModel{
            Db: db,
        }

        product := entities.Product{
            Id:       3,
            Name:     "def",
            Price:    888,
            Quantity: 999,
            Status:   false,
        }
        rowsAffected, err2 := productModel.Update(&product)
        if err2 != nil {
            fmt.Println(err2)
        } else {
            fmt.Println("Rows Affected:", rowsAffected)
        }

    }
}
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