Gorm

The fantastic ORM library for Golang

Add module to project :

go get -u gorm.io/gorm

Connect to mysql db :

Add mysql driver for gorm.

go get -u gorm.io/driver/mysql

Connect db.

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

type Product struct {
  gorm.Model
  Code  string
  Price uint
}

func New() (*gorm.DB, error) {
    dsn := "root@tcp(127.0.0.1:3306)/db_name?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    return db, err
}

Insert data:

db.Create(&Product{Code: "D42", Price: 100})

Retrieve data:

// Read one data
var product Product
db.First(&product, 1) // find product with integer primary key
db.First(&product, "code = ?", "D42") // find product with code D42

var result []entity.Product
err := f.db.Table("product").
    Order("id desc").
    Find(&result).Error

Update data:

// Update - update product's price to 200
db.Model(&product).Update("Price", 200)
// Update - update multiple fields
db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

Delete data:

// Delete - delete product
db.Delete(&product, 1)